swap函数cannot bind non-const lvalue reference of type ‘std::basic_string<char>&‘ to an rvalue of type

cannot bind non-const lvalue reference of type ‘std::basic_string&’ to an rvalue of type
错误发生于swap函数。
我的编译工具是gcc,win10 环境 可能你的其他编译工具能够通过
翻译错误: 无法将函数参数中的std::basic_string& 绑定到这个s,str()

void stream_read_streambuf_stringstream(std::istream& f, std::string& result) 
{
    
     
    std::stringstream s;
    std::copy(std::istreambuf_iterator<char>(f.rdbuf()),
    std::istreambuf_iterator<char>(),
    std::ostreambuf_iterator<char>(s) );
    //const string &str3=s.str();//延长stringstream 对象返回的字符串的生命周期
    //std::swap(result,const_cast<string&>(str3));//去掉const
    std::swap(result,s.str());
}

修改后的代码:

void stream_read_streambuf_stringstream(std::istream& f, std::string& result) 
{
    
     
    std::stringstream s;
    std::copy(std::istreambuf_iterator<char>(f.rdbuf()),
    std::istreambuf_iterator<char>(),
    std::ostreambuf_iterator<char>(s) );
    const string &str3=s.str();//延长stringstream 对象返回的字符串的生命周期
    std::swap(result,const_cast<string&>(str3));//去掉const
}

猜你喜欢

转载自blog.csdn.net/bin_bujiangjiu/article/details/112647935