For the second part of this document, please refer to the overview section: http://www.cnblogs.com/harrywong/p/4220233.html.
Move semantics
Suppose X is a class that contains a pointer or a handle to some resource (handle). Writing m_pResource . By this resource, I mean that including construction, cloning, and destruction are seriously considered, a good example is std::vector. It can contain a collection of objects in an allocated array of memory. Then, logically, the copy assignment operators for x are generally as follows:
x& X::operatorconst & RHS) { // [...] // the resource that the destructor M_presource points to. // make a clone of the resource that Rhs.m_presource points to, and then // and attach it to the M_presource. // [...]}
This also applies to copy constructors because of similar reasons. Now assume that x is used as follows:
X foo (); x x; // x may be used in many ways x = foo ();
Before the last line is executed:
- To analyze the resources held by X.
- A temporary variable returned from Foo was cloned
- The temporary variable is deconstructed and the resource it points to is freed.
Obviously, this is possible, but there is a more efficient way to swap x and temporary variables for pointers to resources or handles (handles), and then let the destructor of the TEMP variable deconstruct the resource of the original X. In other words, in this particular case, the right-hand side of the assigned value is the rvalue. We want the copy constructor to behave as follows:
// [...] // Exchange M_presource and Rhs.m_presource // [...]
This is called move semantics . In c++11, this conditional behavior can be implemented with the following overloads:
x& X::operator= (<mystery type> rhs) { // [...] // Exchange This->m_presource and Rhs.m_presource // [...] }
Since we have defined an overload for the copy constructor, our "mystery type" must be essentially a reference: we certainly want the value on the right hand to be passed to us by reference. Furthermore, we expect the mystery type to behave as follows: When faced with an overloaded selection of the original reference type and mystery type, the rvalue must first select the overloads of the mystery type, while the Lvalue must first select the original reference type.
If you now realize that the "rvalue reference" above is referring to "mystery type", then you have essentially seen the definition of rvalue reference.
Translation "c++ Rvalue References explained"c++ rvalue reference detailed part2:move semantics