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.
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.
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.
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.
For the post c++11 age, things are a bit more interesting. You can bind temporaries to non-const rvalue
references:
std::string&& x = "Test"; //Okay and still extends the lifetime of the temporary
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With