On this page
Move Semantics
Prev: Structured Bindings | Up: builtins | Next: Concepts (C++20)
Rel: References & Rvalues, Value Categories & Move Semantics, std::unique_ptr
Ref: cppreference — Move Constructors
Tags: #public #prog #cpp #builtins #tier/standard
Overview
Move semantics (C++11) let objects transfer ownership of heap buffers or handles (O(1) pointer swap) instead of deep copying when the source is a temporary or explicitly marked movable via std::move.
Notes & Pitfalls
std::movedoesn't move anything—it casts to an rvalue reference (T&&) so the target's move constructor/assignment can steal internal buffers.- Don't
return std::move(local);: That disables NRVO (copy elision); returnlocalby name. Mark move constructorsnoexceptsostd::vectormoves instead of copying on reallocation.
Example
#include <cassert>
#include <string>
#include <utility>
int main() {
std::string a = "heap-allocated string payload";
std::string b = std::move(a); // steals buffer without copying
assert(b == "heap-allocated string payload");
}
Linked from
Related notes
- tuts/cpp/builtins/concepts Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/references_and_rvalues Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/structured_bindings Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/language_and_raii/value_categories_and_move_semantics Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/memory/unique_ptr Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/containers/vector links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/auto shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #builtins, #cpp, #prog, #tier