Move semantics

C++11 provides move semantics through a move constructor and a move assignment operator, which are called when a temporary object is used either to create another object or to be assigned to an existing object. In both cases, because the temporary object will not live beyond the statement, the contents of the temporary can be moved to the other object, leaving the temporary object in an invalid state. The compiler will create these functions for you through the default action of moving the data from the temporary to the newly created (or the assigned to) object.

You can write your own versions, and to indicate move semantics these have a parameter that is an rvalue reference (&&).

If you want the compiler to provide you with a default version of any of these methods, you can provide the prototype in the class declaration suffixed with =default. In most cases, this is self-documenting rather than being a requirement, but if you are writing a POD class you must use the default versions of these functions, otherwise is_pod will not return true.

If you want to use only move and never to use copy (for example, a file handle class), then you can delete the copy functions:

    class mytype 
{
int *p;
public:
mytype(const mytype&) = delete; // copy constructor
mytype& operator= (const mytype&) = delete; // copy assignment
mytype&(mytype&&); // move constructor
mytype& operator=(mytype&&); // move assignment
};

This class has a pointer data member and allows move semantics, in which case the move constructor will be called with a reference to a temporary object. Since the object is temporary, it will not survive after the move constructor call. This means that the new object can move the state of the temporary object into itself:

    mytype::mytype(mytype&& tmp) 
{
this->p = tmp.p;
tmp.p = nullptr;
}

The move constructor assigns the temporary object's pointer to nullptr, so that any destructor defined for the class does not attempt to delete the pointer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset