Join Bill Weinman for an in-depth discussion in this video What is move semantics?, part of C++ Move Semantics.
- Move Semantics represents an important and valuable addition to the C++ language. Move Semantics was added to the language with the C++11 standard. To illustrate the need for Move Semantics, let's consider this simple example, without Move Semantics. Here's a function that takes an object of type T and returns an object of the same type T. This function uses call-by-value, which means that when this function is called an object must be constructed to be used by the function.
Because the function also returns by value, another New object is constructed for the return value. At this point, two New objects have been constructed. One of them is a temporary object that's only used for the duration of the function. When the New object is created from the return value, the copy constructor is called to copy the contents of the Temporary object to the new object b. After the function completes, the Temporary object used in the function goes out of scope and is destroyed.
Let's consider what a copy constructor does. It must first initialize the object, then copy the relevant data from the old object to the new object. Depending on the class, perhaps it's a container with a lot of data, this could represent a substantial amount of time and memory usage. With Move Semantics, it's now possible to mitigate most of this work by simply moving the data, rather than copying it. Moving the Data simply involves re-associating the Data with the new object.
No copy takes place at all. This is accomplished with something called an rvalue reference. A traditional C++ reference type is now called an lvalue reference, in order to distinguish it from the new rvalue type. An rvalue reference works very much like an lvalue reference with one important distinction. An rvalue reference can be moved. An lvalue reference cannot. Move Semantics creates a number of significant opportunities for gains in both efficiency and memory usage.
Let's take a look at how this powerful new language feature works.