C++C++ Explainer
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 steal
2

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
stepcost
allocateO(n)
memcpyO(n)
both own data2 buffers
→
Move
stepcost
steal pointerO(1)
null the sourceO(1)
one owner1 buffer
COPYsrc [1,2,3]dst [1,2,3]MOVEsrc (empty)dst [1,2,3]move steals the buffer — no allocation
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 reading
WATCH 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?