Move Semantics
As read before, move semantics in cpp is nothing but working with something temporary and moving (pointing) it to some other variable to keep this data alive.
Note: temperary is denoted as
&&
in a cpp program.
Here is an example:
Let me explain the key points of this example:
We've defined a
MyString
class with both copy and move semantics.Copy operations (constructor and assignment) create a new buffer and copy the data.
Move operations (constructor and assignment) transfer ownership of the buffer without copying data.
In the
main()
function:str2 = str1
uses copy constructionstr3 = std::move(str1)
uses move constructionstr4 = str2
uses copy assignmentstr4 = createString()
uses move assignment (becausecreateString()
returns a temporary)
The move operations are more efficient because they avoid allocating new memory and copying data. Instead, they simply transfer ownership of the existing data.
After a move operation, the source object (
str1
in the move construction case) is left in a valid but unspecified state. In this implementation, we set its pointer tonullptr
and length to 0.The
noexcept
specifier on move operations is a guarantee that these operations won't throw exceptions, which allows for further optimizations by the compiler.
When you run this program, you'll see which constructors and assignment operators are called in each case. The move operations will be used for temporary objects (like the one returned by createString()
), resulting in better performance.
This example demonstrates how move semantics can improve efficiency by avoiding unnecessary copying, especially when dealing with temporary objects or explicitly using std::move
.
Last updated