繁体   English   中英

C ++,为什么可以将右值传递给以左值引用为参数的函数

[英]C++, why can you pass rvalue to a function which takes lvalue reference as argument

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

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;
}

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

std::string tmp = "Test";
func(tmp);

就像我需要创建参考一样。

std::string tmp = "Test";
std::string& x = tmp;

这与传递给函数无关,而与对const对象的lvalue引用有关。

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

以上尝试将临时绑定到非常量引用。 如果我们要对其进行调整,它将格式正确:

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

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

void func(std::string& x)

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


对于后c ++ 11时代,事情会变得更加有趣。 您可以将临时绑定到非常量rvalue引用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM