C++ · 3 · Memory & Smart Pointers13 / 36 · 36%
Move Semantics: lvalues, rvalues & std::move
Transfer ownership instead of copying buffers.
Examples: T&&, std::move, move ctor
shortcuts: ← prev · → next · M mark
1
lvalue vs rvalue
An lvalue has a name and an address; an rvalue is a temporary.
Example
example
std::string s = "hi"; // s is an lvalue
get_name(); // the returned temporary is an rvalue
void f(const std::string&); // binds to both
void f(std::string&&); // binds to rvalues only — can steal2
Move Constructor
Steal the pointer, leave the source valid but empty.
Example
example
class Buffer {
char* data_ = nullptr;
size_t size_ = 0;
public:
Buffer(Buffer&& o) noexcept
: data_(o.data_), size_(o.size_) {
o.data_ = nullptr; // source must stay destructible
o.size_ = 0;
}
};Copy
| step | cost |
|---|---|
| allocate | O(n) |
| memcpy | O(n) |
| both own data | 2 buffers |
Move
| step | cost |
|---|---|
| steal pointer | O(1) |
| null the source | O(1) |
| one owner | 1 buffer |
ownership transfer
3
std::move Is a Cast
It moves nothing — it just says "you may steal from this".
Example
example
std::string a = "hello";
std::string b = std::move(a); // b steals a's buffer
// a is valid but unspecified — assign to it before readingWATCH OUT
Never std::move a value you still need, and never move a const object — it silently copies.
4
noexcept Matters
std::vector only moves your type on reallocation if the move ctor is noexcept.
Interview question
Why must a move constructor be noexcept?