![]() |
VOOZH | about |
Move semantics is a feature that allows our program to transfer ownership of resources (like memory, files, etc.) from one object to another instead of copying them. This results iin:
Normally when we copy an object that owns a resource, both objects must mange separate copies of that resource.
But copying is expensive - especially for big data.
With move semantics we can transfer the resource from one object to another, leaving the first object in the "moved-from" state which means it's still a valid object but it no longer owns the original resource (like text in a string or data in a vector).
Example:
Original: '' Copy: 'Hello, World!' Moved: 'Hello, World!'
Feature | Copy | Move |
|---|---|---|
What it does | Creates a full duplicate | Transfers ownership |
Speed | Slower (copies memory/resources) | Faster (just move pointers) |
Old object | Still holds a valid copy | Becomes empty or "moved-from" |
When used | When original is still needed | When original is temporary/disposable |
Code Example | std::string b=a; | std::string b=std::move(a); |
To understand move semantics, we need to know what lvalues and rvalues are:
Move Semantics is about transferring ownership of resources, we can only do that safely if we know no one else needs it anymore.
That's why :
Feature | Lvalue Reference (T&) | Rvalue Reference (T&&) |
|---|---|---|
Binds to | Named objects (lvalues) | Temporary objects (rvalues) |
Can Appear On | Left or right side of assignment | Only on right side (usually temporary) |
Syntax | Single ampersand & | Double ampersand && |
Usage | To refer to existing variables | To enable move semantics and bind temporaries |
Modifies | The original named object | Can "steal" resources from temporaries. |
Common Use Case | Passing objects by reference to avoid copying. | Implementing move constructors and move assignments. |
One of the most practical and important uses of move semantics is in standard library containers like std::vector, std:: map, std:: set and others. These containers use move operations internally to improve performance and avoid unnecessary copying.
STL containers like std::vector use move semantics to improve performance in two main cases:
When a container grows and needs more space, it reallocates memory transfers existing elements.
If the element type supports move, the container moves elements instead of copying them - making reallocation faster.
Move semantics are also used when inserting elements:
Example:
These operations reduce unnecessary copying and make insertion more efficient.