我正在使用std :: stringstream来构造一个字符串,然后尝试传递完成的字符串作为一个函数的参考,它需要一个参数std ::字符串&。从std :: stringstream传递std :: string参数作为参数
我在GCC得到一个编译错误:
../src/so.cpp:22:21: error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string<char>&}’ from an rvalue of type ‘std::basic_stringstream<char>::__string_type {aka std::basic_string<char>}’
../src/so.cpp:12:6: error: in passing argument 1 of ‘void myFunc(std::string&)’
make: *** [src/so.o] Error 1
相同的代码在Windows VS2012编译,但无法在我的Linux和Android版本。这是什么原因?
我可以通过暂时将ss.str()分配给一个临时std :: string,然后通过引用传递该字符串来解决此问题,但这看起来有点愚蠢。干净地做这件事的正确方法是什么?
#include <iostream>
#include <sstream>
void myFunc (std::string& msg)
{
std::cout << msg << std::endl;
}
int main (void)
{
std::stringstream ss;
ss << "this is a test";
myFunc (ss.str()); // Fails
std::string s = ss.str();
myFunc (s); // Pass
return 0;
}
将警告等级设置为'/ W4',VS会告诉你在该线路上正在使用非标准的分机。 – Praetorian 2015-02-10 21:05:15