Topic 18 of 27 · Intermediate
Why doesn’t std::move necessarily move an object?
std::move casts an expression to an rvalue reference category; the receiving constructor or assignment operator decides whether a move actually occurs.
C++20; compile with g++ -std=c++20.
Detailed answer
std::move casts an expression to an rvalue reference category; the receiving constructor or assignment operator decides whether a move actually occurs.
Moving from a const object often calls a copy constructor because typical move constructors need a non-const rvalue reference. Moving a built-in integer is no different from copying it.
Standard-library moved-from objects are generally valid but unspecified unless a stronger postcondition is documented. Reassign or destroy them; do not assume every moved-from string is empty.
Internal working
Overload resolution selects T&& or const T& based on the expression category and available operations. noexcept moves let containers preserve exception guarantees efficiently during reallocation.
Practical scenario
A developer writes std::move on a const vector and expects zero-copy ownership transfer; the copy overload is selected.
#include <vector>
#include <utility>
#include <iostream>
int main(){std::vector<int> a{1,2};auto b=std::move(a);std::cout<<b.size()<<"\n";}Common mistakes
- Reading a moved-from value with assumed contents.
- Adding std::move to a return when it prevents NRVO.
Key takeaways
- std::move is a cast.
- Overload resolution determines transfer.
- Honor moved-from contracts.
Follow-up challenges
- Why should a move constructor often be noexcept?
- What distinguishes forwarding from moving?