Thomas Becker has a great article explaining C++11′s rvalue references and how they allow move semantics and perfect forwarding.

I particularly liked his summary of the 3 things you need to remember about rvalue references:

  1. By overloading a function like this:
    
    void foo(X& x); // lvalue reference overload
    void foo(X&& x); // rvalue reference overload
    


    you can branch at compile time on the condition “is foo being called on an lvalue or an rvalue?” The primary (and for all practical purposes, the only) application of that is to overload the copy constructor and copy assignment operator of a class for the sake of implementing move semantics. If and when you do that, make sure to pay attention to exception handling, and use the new noexcept keyword as much as you can.

  2. std::move turns its argument into an rvalue.
  3. std::forward allows you to achieve perfect forwarding if you use it exactly as shown:
    
    template<typename T, typename Arg>
    shared_ptr<T> factory(Arg&& arg)
    {
        return shared_ptr<T>(new T(std::forward<Arg>(arg));
    }

I also like his definition of lvalues and rvalues in the introduction:

The original definition of lvalues and rvalues from the earliest days of C is as follows: An lvalue is an expression e that may appear on the left or on the right hand side of an assignment, whereas anrvalue is an expression that can only appear on the right hand side of an assignment.

In C++, this is still useful as a first, intuitive approach to lvalues and rvalues. However, C++ with its user-defined types has introduced some subtleties regarding modifiability and assignability that cause this definition to be incorrect. There is no need for us to go further into this. Here is an alternate definition which, although it can still be argued with, will put you in a position to tackle rvalue references: An lvalue is an expression that refers to a memory location and allows us to take the address of that memory location via the & operator. An rvalue is an expression that is not an lvalue. 

Tagged with:  

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>