从std :: stringstream传递std :: string引用作为参数

Chr*_*ris 4 c++ parameters reference

我使用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
Run Code Online (Sandbox Code Playgroud)

在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;
}
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 6

问题是myFunc采用非const左值引用.stringstream::str()按值返回字符串.您不能在标准C++中将临时绑定到非const左值引用,但VS有一个允许此扩展的"扩展".这就是它编译VS而不是其他编译器的原因.

const另一方面,左值引用可以绑定到右值.所以修改你的功能会使它工作:

void myFunc (const std::string &msg) { /* as before */ }
Run Code Online (Sandbox Code Playgroud)