C++,为什么可以将rvalue传递给以lvalue引用为参数的函数?

6
为什么您可以将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;
}

在尝试之前,我认为在调用函数之前需要创建一个字符串变量。
std::string tmp = "Test";
func(tmp);

与创建参考文献所需的步骤相似。
std::string tmp = "Test";
std::string& x = tmp;

3
我不明白你的意思。std::string&const std::string& 不是同一件事情。 - songyuanyao
1个回答

13

问题不在于将其传递给函数,而在于对 const 对象的 lvalue 引用。

std::string& x = "Test"; //fails to compile

上述尝试将临时值绑定到非const引用。如果我们进行微调,则会形成良好的形式:

std::string const& x = "Test"; // compiles

现在它延长了临时对象的生命周期,直到引用超出作用域,符合C++标准规定。
有了这个知识,我们可以通过将原型更改为以下内容来使您的函数无法编译:

void func(std::string& x)

现在函数参数不能绑定到临时对象,因为它接受的是非const引用。


对于C++11之后的情况,事情变得更加有趣。您可以将临时对象绑定到非const rvalue引用:

std::string&& x = "Test"; //Okay and still extends the lifetime of the temporary

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接