C++,为什么你可以将rvalue传递给一个以左值引用作为参数的函数

cha*_*255 1 c++

为什么你可以将rvalue传递给需要引用的函数?

void func(const std::string& x)
{
    std::cout << x << std::endl;
}

int main()
{
    std::string& x = "Test"; //fails to compile
    func("Test"); //works
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在尝试之前,我认为在调用func之前我需要创建一个字符串变量.

std::string tmp = "Test";
func(tmp);
Run Code Online (Sandbox Code Playgroud)

就像我需要创建一个引用一样.

std::string tmp = "Test";
std::string& x = tmp;
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 8

它不是传递给函数,而是关于对象的lvalue引用const.

std::string& x = "Test"; //fails to compile
Run Code Online (Sandbox Code Playgroud)

上面尝试将临时绑定到非const引用.如果我们要调整它,它将很好地形成:

std::string const& x = "Test"; // compiles
Run Code Online (Sandbox Code Playgroud)

现在它延长了临时的生命周期,直到引用超出范围,这是c ++标准的要求.
知道了这一点,我们可以通过将原型更改为:来使您的函数无法编译:

void func(std::string& x)
Run Code Online (Sandbox Code Playgroud)

现在,functions参数无法绑定到临时对象,因为它接受非const引用.


对于post c ++ 11时代,事情会更有趣.您可以将临时对象绑定到非const rvalue引用:

std::string&& x = "Test"; //Okay and still extends the lifetime of the temporary
Run Code Online (Sandbox Code Playgroud)