Search code examples
c++c++11rvalue-reference

How is it possible to get a reference to an rvalue?


I have used std::move and std::forward in C++. My question is: how are these functions actually implemented by the standard library?

If an lvalue is something you can get the address of, and an rvalue is exclusively not an lvalue, how can you actually implement these references?

Do these new facilities allow for something like:

auto x = &(3); 

or something like that? Can you get a reference to an rvalue that isn't just a std::move/forward returned lvalue?

Hopefully these questions make sense. I couldn't find good information on Google, just tutorials on perfect forwarding, etc.


Solution

  • I cannot call a function: void foo(string* bar) like this: foo(&string("Hello World!")) or I get an error:

    error: taking address of temporary

    I also cannot call a function: void foo(string& bar) like this: foo(string("Hello World!")) or I get an error:

    error: invalid initialization of non-const reference of type 'std::string& {aka std::basic_string&}' from an rvalue of type 'std::string {aka std::basic_string}'

    What C++11 has provided me the ability to do is to make an rvalue reference, so I can call a function: void foo(string&& bar) like this: foo(string("Hello World!"));

    Furthermore, internally to foo I can get the address of the object passed in by an rvalue reference:

    void foo(string&& bar){
        string* temp = &bar;
    
        cout << *temp << " @:" << temp << endl;
    }
    

    It seems like the OP has a really good grip on rvalues. But this explanation of them was helpful to me, and may be to others. It goes into a bit of detail about why C++03 allowed constant references to rvalues, versus C++11's rvalue references.