[英]C++, why can you pass rvalue to a function which takes lvalue reference as argument
Why is is that you can pass an rvalue to a function which requires a reference? 为什么可以将右值传递给需要引用的函数?
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;
}
Before trying it I thought I would need to create a string variable before calling func. 在尝试之前,我认为我需要在调用func之前创建一个字符串变量。
std::string tmp = "Test";
func(tmp);
Much like I would need to in order to create a reference. 就像我需要创建参考一样。
std::string tmp = "Test";
std::string& x = tmp;
It's not about passing to a function, it's about the lvalue
reference being to a const
object. 这与传递给函数无关,而与对
const
对象的lvalue
引用有关。
std::string& x = "Test"; //fails to compile
The above attempts to bind a temporary to a non-const reference. 以上尝试将临时绑定到非常量引用。 If we were to tweak it, it would be well formed:
如果我们要对其进行调整,它将格式正确:
std::string const& x = "Test"; // compiles
Now it extends the lifetime of the temporary until the reference goes out of scope, as mandated by the c++ standard. 现在,它可以延长临时文件的寿命,直到引用超出c ++标准要求的范围。
Knowing this, we can make your function fail to compile as well by changing the prototype to: 知道了这一点,我们可以通过将原型更改为以下内容来使您的函数无法编译:
void func(std::string& x)
Now the functions parameter can't bind to temporary objects, since it accepts by a non-const reference. 现在,functions参数无法绑定到临时对象,因为它由非const引用接受。
For the post c++11 age, things are a bit more interesting. 对于后c ++ 11时代,事情会变得更加有趣。 You can bind temporaries to non-const
rvalue
references: 您可以将临时绑定到非常量
rvalue
引用:
std::string&& x = "Test"; //Okay and still extends the lifetime of the temporary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.