Move semantics and templates in C++, explained with real code
Copies and moves, passing by value then moving, emplace, function and class templates, forwarding constructor arguments, and storing callables with std::function.
Generic, efficient C++ rests on two ideas: moving instead of copying, and templates that work for any type. Both show up as soon as you write a container, a pool or a queue.
Copies and moves
Copying a std::string or std::vector copies all its elements. Moving one just takes over its
buffer, which is O(1):
std::vector<int> a(1'000'000, 7);
std::vector<int> b = a; // copy: a million ints
std::vector<int> c = std::move(a); // move: three pointers; a is now empty-ishstd::move doesn't move anything itself; it marks a as "you may steal from this". After the
move, don't read a again until you assign to it.
Pass by value, then move
For a function that keeps its argument, take it by value and move it into place:
void Queue::push(std::string message) { // caller's copy or move happens here
std::lock_guard lock(mutex_);
items_.push_back(std::move(message)); // no second copy
}
queue.push(text); // copies once (the caller keeps text)
queue.push(std::move(text)); // copies neverFor a function that only reads its argument, const std::string& (or std::string_view) is
still right.
Moving into containers
emplace_back builds the element directly inside the container from constructor arguments:
std::vector<std::pair<std::string, int>> v;
v.emplace_back("apples", 3); // constructs the pair in placeSome types can only be moved, never copied: std::unique_ptr, std::thread, std::future,
std::packaged_task. Containers of them work fine as long as you move elements in and out.
Function templates
A template is a recipe the compiler instantiates for each type you use:
template <typename T>
const T& clamp_to(const T& value, const T& low, const T& high) {
return value < low ? low : (high < value ? high : value);
}Template definitions live in the header: the compiler needs the full body wherever the template is used.
Class templates
template <typename T>
class ObjectPool {
public:
explicit ObjectPool(std::size_t capacity);
// ...
private:
BlockPool blocks_{sizeof(T), alignof(T), /*count*/ 64};
};sizeof(T) and alignof(T) give the size and alignment of the type the pool was instantiated
with: exactly what a memory pool needs to hand out correctly aligned
blocks.
Forwarding arguments
To construct a T from whatever arguments the caller passes, forward them unchanged:
template <typename T>
template <typename... Args>
T* ObjectPool<T>::create(Args&&... args) {
void* block = blocks_.allocate();
return ::new (block) T(std::forward<Args>(args)...); // placement new, see RAII guide
}Args&&... plus std::forward passes each argument on as it came in: temporaries are moved,
named objects are copied (or bound by reference). See
raw memory, done carefully.
Storing callables with std::function
To keep "something to call later" (a lambda, a function, a functor) in a container:
std::deque<std::function<void()>> tasks;
tasks.emplace_back([path] { compress(path); });std::function must be copyable, so it can't hold a move-only object such as a
std::packaged_task. Wrap it in a std::shared_ptr, or use C++23's std::move_only_function
where your compiler has it:
auto task = std::make_shared<std::packaged_task<int()>>(std::move(work));
std::future<int> result = task->get_future();
tasks.emplace_back([task] { (*task)(); });That's the core of submitting work to a thread pool for Batchworks.
Questions and answers
- Does std::move move anything?
- No. std::move is a cast that says 'you may steal from this object'. The actual move happens in the move constructor or move assignment that the cast selects. After a move, the source is valid but unspecified, so only assign to it or destroy it.
- Why do templates have to be defined in the header?
- The compiler generates code for a template only when it sees it used with concrete types, and it needs the full definition at that point. So template bodies go in the header, not a .cpp file.
Practise it in a project
These projects put this guide to work, with tickets, tests and code review.
Pixelforge
Memory pools for Pixelforge
Stop frame stutters in Pixelforge's engine with a fixed-size block allocator: an intrusive free list, alignment, misuse detection, then a typed object pool with RAII handles.
- manual memory management
- alignment
- placement new
- RAII and templates
Batchworks
A thread pool for Batchworks
Replace thread-per-job with a fixed pool of workers: a shared task queue, graceful shutdown, failure accounting, futures for results and a parallel_for.
- threads
- task queues
- futures
- shutdown semantics
Relaybox
A message queue for Relaybox
Build the bounded, blocking, closable queue between Relaybox's receivers and senders: mutexes, condition variables, backpressure, shutdown, timeouts and batches.
- threads
- mutexes
- condition variables
- backpressure
Draftboard
Undo and redo for Draftboard
Give Draftboard's editor an undo history that behaves the way writers expect: reversible commands, typing that undoes a word at a time, grouped edits and a bounded history.
- command pattern
- stacks
- inverse operations
- bounded history