Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
like image 727
chasep255 Avatar asked Dec 14 '22 01:12

chasep255


1 Answers

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
like image 80
StoryTeller - Unslander Monica Avatar answered Dec 16 '22 15:12

StoryTeller - Unslander Monica