26 Oct 2026
Move Semantics
Ownership, Overloads, Efficiency
Study notes found from Andreas Fertig lecture from 2022.
1. &, const &, and &&: Which Overload Is Called?
void Fun(std::vector<int>&) { std::cout << "byRef\n"; }
void Fun(const std::vector<int>&) { std::cout << "byConstRef\n"; }
void Fun(std::vector<int>&&) { std::cout << "byMoveRef\n"; }
std::vector<int> v{2, 3, 4};
const std::vector<int> cv{5, 6, 7};
Fun(v); // byRef
Fun(cv); // byConstRef
Fun({3, 5, 6}); // byMoveRef
Fun(std::move(v)); // byMoveRef
- An lvalue identifies an object (
v); a prvalue computes a value (std::vector<int>{3,5,6}); an xvalue identifies an object whose resources may be reused (std::move(v)). glvalue means lvalue or xvalue. - An rvalue can bind to
const T&orT&&, but not ordinaryT&. When both exist,T&&wins for a non-const rvalue. Without the&&overload, the temporary callsconst T&. - An xvalue is not necessarily about to die:
std::move(v)does not changev's lifetime. Likewise, merely binding an&¶meter does not move anything.
2. std::move: Ownership Can Outlive Its Original Scope
class Database {
std::vector<int> data;
public:
Database(std::vector<int> v) : data(std::move(v)) {}
};
Database makeDatabase() {
std::vector<int> v(1'000'000, 42);
return Database(std::move(v));
} // local v is destroyed; Database owns its former allocation
RAII ties a resource's cleanup to its owning object's destructor. Here, the vector's heap allocation needs to survive makeDatabase(). Copying one million elements would be O(n); moving a std::vector typically transfers ownership of its buffer in O(1). There are two vector moves here (into the parameter and then the member); the returned Database is constructed directly in the destination in C++17 and later.
std::move itself is only a cast producing an xvalue. A move constructor or move assignment operator actually transfers resources. The source object remains alive and destructible, usually in a valid but unspecified state—not an undefined state.
3. A Resource-Owning string: Copy the Buffer or Exchange Ownership
// Illustrative members of a custom string class:
// size_t mLen{};
// std::unique_ptr<char[]> mData{};
string::string(const string& rhs)
: mLen{rhs.mLen},
mData{std::make_unique<char[]>(rhs.mLen)}
{
std::copy_n(rhs.mData.get(), mLen, mData.get());
}
string::string(string&& rhs) noexcept
: mLen{std::exchange(rhs.mLen, 0)},
mData{std::exchange(rhs.mData, nullptr)}
{}
string& string::operator=(string&& rhs) noexcept
{
if (&rhs != this) {
mLen = std::exchange(rhs.mLen, mLen);
mData = std::exchange(rhs.mData, std::move(mData));
}
return *this;
}
The copy constructor allocates a fresh array and copies mLen characters: a deep copy, O(n). mData.get() produces a pointer value (a prvalue), but that pointer still points to writable memory; std::copy_n(source, count, destination) writes through it.
std::exchange(a, b) returns the old a and replaces a with b. In the move constructor, it transfers the length and unique_ptr, leaving rhs empty; moving the pointer is O(1). In this move assignment operator, it instead hands the destination's old resources back to rhs, so rhs is not necessarily empty.
4. std::move(x) Can Still Copy: Overload Resolution and the Rule of Five
struct A {
A() = default;
A(const A&) { std::cout << "COPY\n"; }
// No move constructor declared
};
A a;
A b = std::move(a); // COPY: const A& can bind to an xvalue
std::move(a) casts a to an xvalue; it does not call a constructor. Only when constructing b does overload resolution look for A(A&&). If none exists, A(const A&) can accept the xvalue, so it copies. If an explicitly deleted move constructor is the best match, construction fails instead of silently copying.
Compiler-generated special members (simplified Rule of Five table):
| User declares | Default ctor | Destructor | Copy ctor | Copy assignment | Move ctor | Move assignment |
|---|---|---|---|---|---|---|
| Nothing | Defaulted | Defaulted | Defaulted | Defaulted | Defaulted | Defaulted |
| Other constructor | Not declared | Defaulted | Defaulted | Defaulted | Defaulted | Defaulted |
| Default constructor | User-declared | Defaulted | Defaulted | Defaulted | Defaulted | Defaulted |
| Destructor | Defaulted | User-declared | Defaulted | Defaulted | Not declared | Not declared |
| Copy constructor | Not declared | Defaulted | User-declared | Defaulted | Not declared | Not declared |
| Copy assignment | Defaulted | Defaulted | Defaulted | User-declared | Not declared | Not declared |
| Move constructor | Not declared | Defaulted | Deleted | Deleted | User-declared | Not declared |
| Move assignment | Defaulted | Defaulted | Deleted | Deleted | Not declared | User-declared |
Not declared means the compiler does not provide that overload; deleted means the operation is forbidden. Defaulted means the compiler generates memberwise behavior if the members allow it. The table describes each declaration in isolation, not combinations; a defaulted operation can itself be defined as deleted for certain member types. A defaulted move constructor that becomes deleted is specially ignored during overload resolution, unlike an explicitly = delete move constructor.
5. noexcept: Why a Growing std::vector Might Copy
struct Object {
Object() = default;
Object(const Object&) { std::puts("copy"); }
Object(Object&&) /* noexcept */ { std::puts("move"); }
};
std::vector<Object> v;
v.emplace_back();
v.reserve(v.capacity() + 1); // Forces reallocation
// Without noexcept: typically "copy"; with noexcept: "move"
During reallocation, moving an old element might modify it and then throw, leaving the original vector unable to recover its previous contents. To preserve the strong exception guarantee, std::vector typically copies existing elements when moving might throw and copying is available. Declaring the move constructor noexcept makes moving the preferred safe option. The newly inserted temporary in the original push_back(Object{}) example can still be moved even when the old elements are copied.
6. T&& and std::forward<T>: Preserve the Caller's Intent
template<typename T>
void Innocent(T&& value) {
std::string local = std::forward<T>(value);
}
std::string s = "A long string that exceeds SSO...";
Innocent(s); // T = std::string& -> copy; s survives unchanged
Innocent(std::move(s)); // T = std::string -> move; s may change
Innocent(std::string{"Hello"}); // T = std::string -> move temporary
When T is deduced, T&& is a forwarding reference: for an lvalue argument, T becomes string&, and string& && collapses to string&; for an rvalue, T becomes string, yielding string&&. Yet the named expression value is always an lvalue, even when its type is string&&. std::forward<T>(value) restores the caller's original value category.
Inside Innocent |
Caller passed lvalue | Caller passed rvalue |
|---|---|---|
local = value |
Copy | Copy |
local = std::move(value) |
Move (surprising!) | Move |
local = std::forward<T>(value) |
Copy | Move |
Why not always std::move? Innocent(s) never signaled permission to consume s. Moving may leave it empty, whether the string uses heap memory or small-string optimization (SSO). std::forward avoids this surprise.
7. Ref-Qualified Methods: Return an Lvalue or Xvalue Appropriately
// Member functions of the custom string class
string& append(const char* s) & {
Concat(s);
return *this;
}
string&& append(const char* s) && {
Concat(s);
return std::move(*this);
}
string s{"Hello"};
s.append(", world!"); // & overload: returns string&
string s2 = string{"Hello"}.append("!"); // && overload: returns string&&
The trailing & or && qualifies the calling object, not the parameter. An ordinary named s selects the & overload; a temporary selects &&. Even in an &&-qualified method, *this is an lvalue expression, so std::move(*this) is needed to return an xvalue. The actual move happens when s2 is initialized, not when std::move is called. The temporary remains alive through that statement, but the returned reference must not escape it.