Move semantics and perfect forwarding basics
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Copying is sometimes wasteful
Consider a function that builds a big vector of a million numbers and returns it. If every return copied the whole vector, C++ would be too slow to use. Move semantics, added in C++11, is the feature that makes this cheap. The idea is easy to state: if the source object is about to be thrown away anyway, steal its insides rather than copying them.
Lvalues and rvalues
Two informal categories help. An lvalue is something with a name and an address that stays around: a variable. An rvalue is a temporary with no name that will vanish at the end of the statement: the result of a + b, or the value returned from a function.
int x = 5; // x is an lvalue; 5 is an rvalue
std::string a{"hello"};
std::string b = a; // a is an lvalue: copy
std::string c = std::string{"hi"} + "!"; // right side is a temporary: can be moved from
The type T&& is an rvalue reference. It can bind to temporaries. That lets a function tell apart "I was given something I may plunder" from "I was given something someone still needs".
A class that owns memory
To see what a move really is, here is a small buffer class that owns an array. Normally you would use a std::vector and write none of this (the rule of zero). Writing it once shows what the standard library does for you.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <utility>
class Buffer {
public:
explicit Buffer(std::size_t n) : size_{n}, data_{new int[n]{}} {}
~Buffer() { delete[] data_; }
Buffer(const Buffer& other) // copy: allocate and copy contents
: size_{other.size_}, data_{new int[other.size_]} {
std::copy(other.data_, other.data_ + size_, data_);
std::cout << "copy\n";
}
Buffer(Buffer&& other) noexcept // move: take the pointer
: size_{other.size_}, data_{other.data_} {
other.size_ = 0;
other.data_ = nullptr;
std::cout << "move\n";
}
Buffer& operator=(Buffer other) noexcept { // copy-and-swap: one operator for both
std::swap(size_, other.size_);
std::swap(data_, other.data_);
return *this;
}
std::size_t size() const { return size_; }
private:
std::size_t size_;
int* data_;
};
Buffer make() { return Buffer{1000}; }
int main() {
Buffer a{10};
Buffer b = a; // copy
Buffer c = std::move(a); // move
Buffer d = make(); // no copy or move at all, thanks to copy elision
std::cout << a.size() << " " << c.size() << "\n"; // 0 10
}
The copy constructor allocates new memory and copies every element. The move constructor takes the pointer from the other object and leaves it empty but valid. A move is a few assignments no matter how large the data is. The noexcept matters: std::vector only uses your move constructor when growing if it cannot throw, because otherwise it could not keep its strong guarantee. Forget noexcept and your type is silently copied instead of moved when a vector reallocates.
What std::move actually does
The name is misleading. std::move(x) moves nothing. It is a cast that turns x into an rvalue, saying "I am done with this, you may take its contents". The actual stealing happens in the move constructor or move assignment that then gets chosen.
std::string name{"a long string that lives on the heap, not in the small buffer"};
std::string moved = std::move(name);
// name is now in a valid but unspecified state. Usually empty.
// Assign to it or destroy it, but do not rely on what it contains.
After a move the source is valid but you should not make assumptions about its value. Only do things that are always safe on any object: assign a new value, or let it be destroyed.
Return values: do not write std::move
This surprises people. When you return a local variable by name, the compiler already treats it as movable, and often skips even that move through copy elision (the object is built directly in the caller's place). Writing return std::move(result); usually makes things worse, since it blocks the elision. Just return result;.
std::vector<int> buildNumbers() {
std::vector<int> result;
for (int i = 0; i < 1'000'000; ++i) result.push_back(i);
return result; // cheap: no copy of a million ints
}
This one fact changes how you write code. Return big objects by value. Do not use "output parameters" to dodge copies that no longer happen.
Sink parameters
When a function is going to keep a copy of its argument, such as storing a name in a member, take it by value and move it into place. The caller chooses whether to copy or move.
class Person {
public:
explicit Person(std::string name) : name_{std::move(name)} {}
private:
std::string name_;
};
std::string n{"Asha"};
Person p1{n}; // copies n once
Person p2{std::string{"Bilal"}}; // moves the temporary: no copy
Forwarding references in one paragraph
In a template, T&& with a deduced T is a forwarding reference: it binds to both lvalues and rvalues. std::forward<T>(arg) passes the argument on with its original category intact. This is how std::make_unique and emplace_back hand your constructor arguments to the object without extra copies. You will write it rarely. It helps to recognise it.
template <typename T, typename... Args>
std::unique_ptr<T> myMakeUnique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
The common mistake
Using an object after moving from it and expecting the old value. Another is return std::move(local). A third is marking something const and then trying to move it: moving needs to change the source, so a const object is copied instead, silently. And lastly, writing a move constructor without noexcept.
Try it yourself
- Add a
std::vector<Buffer>tomainandpush_backseveral buffers. Count how many "copy" and "move" lines you get. Removenoexceptfrom the move constructor and run again. - Write
makeBufferthat returns a named local, then another that writesreturn std::move(local). Compare the output with your compiler's optimisation on and off. - Replace
Bufferwith a class that usesstd::vector<int>and delete your special functions. Confirm it still moves correctly.
int x = 5; // x is an lvalue; 5 is an rvalue
std::string a{"hello"};
std::string b = a; // a is an lvalue: copy
std::string c = std::string{"hi"} + "!"; // right side is a temporary: can be moved from
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account