What the compiler's copy does to an owning class
3 min readThe previous lesson's FileHandle deletes its copy operations because two handles on one descriptor would both close it. Every class that owns a resource, a descriptor, a heap buffer, a lock, faces the same question: what happens when someone copies it?
C++ gives every class a default answer. If you declare no copy operations, the compiler writes them for you. A the special member that builds a new object as a copy of an existing one, written T(const T&) copies the source. A the special member that overwrites an existing object with the value of another, written T& operator=(const T&) does the same for an object that already exists. Both are generated when you declare neither, and both copy every member in turn.
Start with a string class that owns a heap buffer. It is deliberately incomplete: it has a constructor and a destructor, but no copy operations of its own, so the compiler fills in the copy.
#include <cstring>
#include <cstddef>
class String {
public:
String(const char* s) : size_(std::strlen(s)), data_(new char[size_ + 1]) {
std::memcpy(data_, s, size_ + 1);
}
~String() { delete[] data_; }
const char* c_str() const { return data_; }
std::size_t size() const { return size_; }
private:
std::size_t size_;
char* data_;
};
Now copy one. The compiler generates a copy constructor and a copy assignment that copy size_ and data_ member by member. data_ is a pointer, so the copy gets the same address, not a new buffer:
String a("hello");
String b = a; // generated copy: b.data_ == a.data_
String c("x");
c = a; // generated assignment: c.data_ == a.data_ (old buffer leaked)
This is a a copy that copies the handle, here a pointer, but not the resource behind it, so original and copy share the resource. When a and b are destroyed, delete[] runs twice on one pointer; the second is undefined behaviour, and glibc prints something like free(): double free detected in tcache 2. The assignment is worse: it overwrites c.data_ without freeing c's buffer, leaking it, then shares a's.
The trap: declaring a destructor does not stop the copy operations from being generated, only the move operations. The resource-aware-looking class double-frees the moment anyone copies it.
POSIX has it built in. dup(fd) returns a new descriptor that refers to the same open file description, so both share the file offset: a shallow copy. open(path) creates a fresh description: a deep copy (TLPI chapter 5). C++ copying is the same idea for any resource a class owns.
Deep copy and the rule of three
3 min readThe fix is to write the copy operations so they allocate and copy the contents, not the pointer. This is a a copy that duplicates the resource itself, so the copy owns a separate, independent resource.
1write the copy constructor
The copy constructor allocates a fresh buffer of the same size and copies the characters into it:
String(const String& other)
: size_(other.size_), data_(new char[other.size_ + 1]) {
std::memcpy(data_, other.data_, other.size_ + 1);
}
Now String b = a; gives b its own buffer holding the same text. Each object owns its memory, and each destructor frees only what it allocated.
2write the copy assignment operator
Assignment is harder because the target already owns a buffer. You must not overwrite the pointer before freeing the old buffer, and you must survive the case where someone assigns an object to itself. The classic safe form allocates first, copies, and only then frees:
String& operator=(const String& other) {
if (this == &other) return *this; // self-assignment guard
char* tmp = new char[other.size_ + 1]; // allocate first: if this throws, *this is unchanged
std::memcpy(tmp, other.data_, other.size_ + 1);
delete[] data_; // now it is safe to drop the old buffer
data_ = tmp;
size_ = other.size_;
return *this;
}
Allocating before deleting gives the basic guarantee you met last lesson: if new throws, the object still holds its old, valid buffer. The self-assignment guard stops a = a from freeing the buffer before reading it.
There is a cleaner modern idiom called copy-and-swap. It takes the argument by value, so the copy or move happens on the way in, then swaps the guts:
String& operator=(String other) { // by value: the copy is made at the call
swap(*this, other); // friend swap, defined in a later section
return *this;
}
You will see swap defined in the section on moved-from objects. For now, the explicit form above is enough to make assignment correct.
3recognize the rule of three
The rule of three says: if a class needs a custom destructor, a copy constructor, or a copy assignment operator, it almost certainly needs all three. The reason is mechanical. A custom destructor means the class owns a resource and must clean it up. A memberwise copy would share that resource. So the two copy operations must be written too. Any one of the three on its own is a sign the other two are missing.
String is the textbook case. The destructor frees data_, so the copies must not share it. You wrote all three. Most classes, by contrast, own nothing directly and need none of the three, a pattern you already know as the rule of zero.
If your class holds only std::string, std::vector, smart pointers and other types that manage themselves, write no destructor and no copy or move operations. The compiler composes the right behaviour from the members, and there is nothing to get wrong. Reach for the rule of three or five only when you wrap a raw resource, as String wraps a char*.
Value categories choose copy or move
3 min readNow you need the vocabulary the language uses to decide between copying and stealing. Every expression has a the classification of an expression as lvalue, prvalue or xvalue, which decides what it may do and which overload it selects. Two questions define the categories: does the expression have an identity (a name, an address you could take), and are its resources safe to move from?
An an expression that names an object and whose value you may still need: a variable, a dereferenced pointer, a string literal has identity and is not movable. You use it again later, so nobody may steal its buffer out from under you. s in the next example is an lvalue.
A a pure rvalue, an expression with no name that computes a value or initializes an object: a literal, an arithmetic result, a temporary returned by value has no identity. String("hi") is a prvalue. It exists only to initialize something and is safe to move from.
An an expiring value: an object that has a name but whose resources you are explicitly done with, such as the result of std::move has identity and is movable. You have said, in effect, "take it."
The two combined groups matter too. A glvalue, short for generalized lvalue, is any expression with identity: the lvalues plus the xvalues. An rvalue is any expression that may be moved from: the prvalues plus the xvalues.
String s("hello"); // s: lvalue, has a name
String t = s; // s is an lvalue, so this copies
String u = String("hi"); // String("hi"): prvalue, safe to steal
String v = std::move(s); // std::move(s): xvalue, safe to steal
This classification drives overload resolution. A class with both operations has two constructors that differ only in how they bind: the copy constructor takes const String&, the move constructor takes String&&. A const String& binds to both lvalues and rvalues. A String&& binds only to rvalues, the prvalues and xvalues. When both exist, an rvalue argument is a better match for String&&, so the move runs; an lvalue matches only const String&, so the copy runs. That is the entire mechanism: the category picks the overload, and the overload picks whether the buffer is copied or stolen.
The fallback matters too. If a class has no move constructor, an rvalue still binds to const String& and is copied. That is why a copy-only type quietly copies even when you ask for a move, a point the special-members section returns to.
Move semantics: steal the buffer instead of copying it
4 min readA deep copy is correct but wasteful when the source is about to die anyway. If you are building b from a temporary, you could just take the temporary's buffer. That is exactly what a move does, and it turns an O(n) copy into an O(1) pointer swap.
A move constructor is written like a copy constructor, but it takes a a reference spelled T&& that binds only to rvalues, marking the parameter as safe to steal from. The body takes the source's pointer, then leaves the source empty so its destructor does not free the buffer you just took.
1write the move constructor
String(String&& other) noexcept
: size_(other.size_), data_(other.data_) { // steal the pointer
other.data_ = nullptr; // the source must not free it
other.size_ = 0;
}
After the move, other owns nothing, and delete[] nullptr is a safe no-op when its destructor runs. The new object owns the buffer that other used to own. That is a the special member String(String&&) that transfers a source's resources into a new object and leaves the source empty.
2write the move assignment operator
The move assignment releases the target's old buffer, then takes the source's:
String& operator=(String&& other) noexcept {
if (this != &other) { // guard against self-move
delete[] data_; // free what *this owns
size_ = other.size_;
data_ = other.data_; // steal the source's buffer
other.data_ = nullptr;
other.size_ = 0;
}
return *this;
}
The self-move guard is defensive: a = std::move(a) is rare but legal, and without the guard you would free a's buffer and then copy the dangling pointer back into itself.
3mark both noexcept
The keyword noexcept promises that the function never throws. A move that only swaps pointers and sets a source to null cannot throw, so it is declared noexcept. If a noexcept function did throw anyway, std::terminate runs and the process dies. Marking moves noexcept is not decoration: the next internals section shows that std::vector refuses to use a move that might throw. The C++ Core Guidelines rule C.66 puts it plainly: make move operations noexcept.
Now the helper everyone uses. std::move is how you turn an lvalue into an xvalue so the move overloads are chosen:
String s("hello");
String t(std::move(s)); // calls the move constructor
Here is the part that surprises beginners: std::move moves nothing. It is a cast and nothing more, static_cast<String&&>(s) written for you. It does not touch s's buffer, does not null any pointer, and does not call the move constructor. All it does is change the expression's category so the next overload resolution picks the move. The actual stealing happens inside the move constructor when it runs.
Because it is only a cast, std::move on a const object changes nothing useful. It yields const String&&, which cannot bind to String&& (that would drop the const), so it binds to const String& and copies. Moving a const object is a silent copy, with no compiler error and often no warning.
Moved-from objects and the swap idiom
3 min readWhat is s after String t(std::move(s));? The standard calls it a the state of an object after its resources were moved out: valid but unspecified, safe to destroy or assign, but not safe to read. You may do two things with a moved-from object, and only two: destroy it, or assign it a fresh value. Everything else is guessing.
String s("old text");
String t(std::move(s));
s = "new text"; // fine: reassignment is always allowed
std::cout << s.c_str(); // fine again: s has a real value now
What you must not do is rely on a moved-from object being empty, or null, or zero-sized. In practice the standard containers leave themselves empty after a move, but the standard does not promise that; a type you write yourself leaves whatever its move operations leave. Our String leaves data_ null and size_ zero, but that is our choice, not a rule. Code that reads s.size() right after a move without reassigning is a bug waiting for a different implementation.
The reassignment guarantee is why moves fit so well with swap, the operation that exchanges two objects' values. The generic std::swap, since C++11, is defined in terms of moves:
template<class T>
void swap(T& a, T& b) {
T tmp(std::move(a)); // move a's value out
a = std::move(b); // move b's value into a
b = std::move(tmp); // move the saved value into b
}
Three moves, and it needs only a move constructor and a move assignment. For String that is three pointer exchanges, which is correct but already more work than it needs to be. A class can swap its own two pointers directly, which is cheaper and can never throw.
friend void swap(String& a, String& b) noexcept {
using std::swap;
swap(a.size_, b.size_);
swap(a.data_, b.data_);
}
The friend lets this free function reach the private members. It is found by argument-dependent lookup, ADL, the rule that a function call like swap(a, b) also searches the namespaces of the argument types. The idiom that uses it is two lines:
using std::swap; // bring std::swap into scope as the fallback
swap(a, b); // unqualified call: finds String's swap via ADL, else std::swap
This is the ADL swap idiom. The unqualified call finds the specialised swap(String&, String&) because it is in the same namespace as String. For a type with no such function, it falls back to the move-based std::swap. The idiom is what copy-and-swap assignment from the deep-copy section relies on: the by-value operator=(String other) calls swap(*this, other), which swaps pointers in O(1).
Save a: move a's value into a temporary, leaving a valid but empty.
Move b into a: a now holds b's old value.
Move the saved value into b: b holds a's old value.
Finish: each object is valid again; the values have been exchanged.
The five special members and their generation rules
5 min readA class has five special members worth caring about: the destructor, copy constructor, copy assignment, move constructor, and move assignment. (A sixth, the default constructor, is generated only when you declare no constructor.) The table is worth memorising; most surprise is in the move column.
| You declare | Default ctor | Copy ctor | Copy assignment | Move ctor | Move assignment |
|---|---|---|---|---|---|
| nothing | generated | generated | generated | generated | generated |
| a destructor | generated | generated (deprecated) | generated (deprecated) | suppressed | suppressed |
| a copy ctor | not generated | yours | generated (deprecated) | suppressed | suppressed |
| a copy assignment | generated | generated (deprecated) | yours | suppressed | suppressed |
| a move ctor | not generated | deleted | deleted | yours | suppressed |
Two rules cause most pain. First, a user-declared destructor, copy, or move suppresses both move operations: declare any one of the five and the compiler writes no moves. That is why the naive String, with a destructor, had copies but no moves. Second, a user-declared move constructor deletes the copy operations.
The word deprecated in the table means the copy is still generated, but the standard flags it as something you probably forgot. Since C++11, a copy constructor or copy assignment implicitly generated alongside a user-declared destructor or copy operation is deprecated, and GCC and Clang warn with -Wdeprecated-copy.
The = default and = delete spellings let you state the table explicitly instead of leaving it to memory. = default asks for the compiler's version even when it would otherwise be suppressed, and = delete removes a member entirely:
class FileHandle {
public:
explicit FileHandle(const std::string& path);
~FileHandle() = default; // the usual close logic, stated elsewhere
FileHandle(const FileHandle&) = delete; // move-only type
FileHandle& operator=(const FileHandle&) = delete;
FileHandle(FileHandle&& other) noexcept; // transfers the descriptor
FileHandle& operator=(FileHandle&& other) noexcept;
private:
int fd_;
};
This is the move-only resource handle the labs ask for. Deleting the copies makes ownership single and obvious, exactly as the RAII lesson promised. The move constructor transfers the descriptor and sets other.fd_ to an invalid value such as -1, so the two objects never both close it.
One subtlety separates two look-alike cases. A suppressed move is simply not declared, and a move request silently falls back to copy. A generated move that is defined as deleted behaves differently.
class Legacy { // a copy-only type: custom copy, no move
public:
Legacy(const Legacy&); // user copy ctor suppresses the implicit move
Legacy& operator=(const Legacy&);
};
struct Wrapper {
Legacy l; // a copy-only member
};
Wrapper declares none of the five, so the compiler tries to generate its move constructor. It cannot: Legacy has no move constructor and is not trivially copyable. So Wrapper's move constructor is declared and defined as deleted. A deleted defaulted move constructor is ignored by overload resolution, so Wrapper b = std::move(a); falls back to the copy constructor and copies the member. Moving silently copies.
Contrast that with writing the deletion yourself:
struct Locked {
Locked(Locked&&) = delete; // user-declared deleted move
Locked(const Locked&) = default;
};
A user-declared deleted move is different: it participates in overload resolution, so Locked b = std::move(a); selects it and fails to compile. A copy-only member disables the move and yields a silent copy; a written = delete yields an error.
Going deeperWhy a deleted defaulted move falls back to copy
The standard deliberately ignores a defaulted-but-deleted move constructor in overload resolution. A deleted move would otherwise prevent initialization from an rvalue when the copy constructor could do the job, so adding a copy-only member would silently break every move far from the member. With the rule, the struct degrades to copying, always correct if slower.
A user-written T(T&&) = delete; is not defaulted. It is an explicit statement that the type must never be moved, not even by copying, which is the right tool for a type other code holds a raw pointer into.
Put the five members together and you get the three rules of thumb. The rule of three: a custom destructor, copy constructor, or copy assignment implies all three. The rule of five: add the two move operations for a type that owns a resource and should be movable. The rule of zero: write none of the five and let members do the work. The three rules are not competing choices; they describe three kinds of class, and the right one follows from whether the class owns a resource directly.
Why moves must be noexcept
3 min readstd::vector grows by buying a bigger buffer, relocating the elements, and freeing the old one, typically doubling the capacity (the factor is implementation-defined). That relocation is where noexcept pays off.
If the element's move constructor is noexcept, the vector moves every element. Each move is an O(1) pointer steal, so growing a vector of a million Strings is a million pointer swaps and a handful of allocations.
With a throwing move, the vector copies instead, to keep the strong exception guarantee: an operation either completes or leaves everything exactly as it was. If moving element 500 of 1000 throws, the first 499 are already stolen from the old buffer and cannot be restored. Copying leaves each source intact, so a throwing copy just abandons the new buffer with the original untouched.
The library encodes this in std::move_if_noexcept, which returns an rvalue reference when the move is noexcept and an lvalue reference otherwise. The vector calls it during reallocation. A missing noexcept is a silent performance bug, not a correctness one: the program works, but every growth deep-copies every element.
You can watch the difference with a small traced type. Give it a static counter for copies and moves, build one without and one with a noexcept move, and push back in a loop:
#include <iostream>
#include <vector>
struct Traced {
static int copies, moves;
Traced() = default;
Traced(const Traced&) { ++copies; } // counts copies
Traced(Traced&&) { ++moves; } // NOTE: not noexcept
Traced& operator=(const Traced&) = default;
Traced& operator=(Traced&&) = default;
};
int Traced::copies = 0;
int Traced::moves = 0;
int main() {
std::vector<Traced> v;
for (int i = 0; i < 100; ++i) v.emplace_back();
std::cout << "copies: " << Traced::copies
<< ", moves: " << Traced::moves << '\n';
}
Typical output (yours will differ):
copies: 100, moves: 0
Because the move constructor is not noexcept, the vector copies during every reallocation, and the move constructor never runs. Add noexcept to that move constructor, rebuild, and the same program prints moves instead of copies. The numbers change on the spot, which is the lab's demonstration.
Allocate a larger buffer: the capacity is exhausted, so a bigger array is requested.
Relocate the elements: each element is moved if its move is noexcept, copied otherwise.
Release the old buffer: the source storage is freed.
Update the bookkeeping: size, capacity, and the data pointer now describe the new buffer.
Going deeperThe strong guarantee, stated precisely
The strong guarantee means that if an operation throws, the state is exactly as if it had never been attempted. For vector reallocation, copying gives this for free: a throwing copy leaves its source intact, so the original buffer is still a valid vector and the new one is discarded. A move does not, because once element 499 has been moved out, the original buffer is no longer the original vector.
A second reason moves are noexcept by convention: a noexcept function enables further optimisations, and a move that only reassigns pointers has nothing to throw. The exceptions are rare. A type whose move must allocate, such as a node-based container with a small-buffer optimisation, may need a throwing move, and then vector's copy fallback is correct.
Perfect forwarding with std::forward
4 min readstd::move is unconditional: it turns anything into an rvalue. A factory needs the opposite. It must hand its arguments to a constructor without changing what they are, so that an lvalue argument is copied and an rvalue argument is moved, exactly as if the caller had constructed the object directly. That is perfect forwarding, and its tool is std::forward.
The first ingredient is a a parameter declared T&& where T is a deduced template type, which binds to both lvalues and rvalues, sometimes called a universal reference. It looks like an rvalue reference but is not one. In template<class T> void f(T&& x), the type T is deduced from the argument: if the caller passes an lvalue String, T is deduced as String&; if the caller passes an rvalue, T is deduced as String.
Then reference collapsing resolves what T&& actually means. The four cases:
| If T is | then T&& collapses to |
|---|---|
| String | String&& |
| String& | String& |
| const String& | const String& |
| String&& | String&& |
Only rvalue-reference to rvalue-reference stays an rvalue reference. Any lvalue reference in the mix wins and the result binds to lvalues. So a forwarding reference deduces to String& for an lvalue argument and String&& for an rvalue, binding correctly to both.
The second ingredient, std::forward<T>(x), restores that deduced category at the point of the call. It is static_cast<T&&>(x): when T is String&, T&& collapses to String& and the result is an lvalue; when T is String, T&& is String&& and the result is an rvalue. The argument passes through unchanged.
Here is the shape of std::make_unique, the factory that constructs a unique_ptr without leaking if the constructor throws:
template<class T, class... Args>
std::unique_ptr<T> make_unique_like(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
Each Args&& is a forwarding reference, and each std::forward<Args>(args) passes that argument on with its original category. An lvalue argument reaches the constructor as an lvalue, so it is copied; an rvalue reaches it as an rvalue, so it is moved.
The standard containers use the same trick. std::vector<String>::emplace_back("hello") forwards the const char* straight into the String constructor inside the vector's storage. No temporary String is built, no move, no copy. The older push_back(String("hello")) builds a temporary and then moves (or elides) it. For a device building a vector of large buffers, emplace_back is the difference between one allocation per element and two.
The contrast with std::move is the point of the whole section. std::move(x) unconditionally says "treat x as an rvalue." Use it on the last use of an object you own, when you want its guts taken. std::forward<T>(x) conditionally preserves the argument's category. Use it inside templates, when you do not know whether the caller's argument was an lvalue or an rvalue and you must pass it on faithfully.
Going deeperstd::forward is a conditional cast
In essence std::forward is:
template<class T>
T&& forward(std::remove_reference_t<T>& x) noexcept { return static_cast<T&&>(x); }
If T is String&, T&& collapses to String& and the function returns an lvalue reference; if T is String, T&& is String&& and it returns an rvalue reference. The lvalue-or-rvalue decision happened earlier, at the forwarding reference where T was deduced; std::forward re-applies it as a cast. There is no runtime work, which is why forwarding is free in the compiled program.
One warning that trips beginners: inside a template, a named parameter is always an lvalue, even one declared T&&. That is why std::forward is needed at all. Writing std::move(args)... in the factory above would move every argument, even an lvalue the caller still needed.
Copy elision: the copies that never happen
4 min readYou met copy elision in the RAII lesson as the reason returned vectors do not copy. Here is the precise version, because it changed in C++17 and it interacts with everything in this lesson.
Return value optimization, RVO, is eliding the construction of a returned temporary. Named return value optimization, NRVO, is eliding the copy or move of a returned local variable with a name. Before C++17 both were optional optimisations: a compiler could do them, but your copy or move constructor still had to exist and be accessible, because the language did not promise the elision would happen.
C++17 changed RVO into a guarantee for prvalues. Returning String{} or String("hi") is no longer "create a temporary, then copy or move it." The expression is a recipe, not an object, and the object is materialized directly in the caller's storage. No copy or move is performed, and none needs to exist:
struct NoCopy {
NoCopy() = default;
NoCopy(const NoCopy&) = delete;
NoCopy(NoCopy&&) = delete;
};
NoCopy make() { return NoCopy{}; } // fine since C++17
NoCopy n = make(); // no copy, no move, no error
This is guaranteed copy elision. It compiles even though both operations are deleted, because neither is called or even required. NRVO for a named local remains optional to this day:
String make_str() {
String s("hello");
return s; // NRVO: usually elided, but not guaranteed
}
The named local s has identity, so the compiler must treat it as an object, and eliding it is still a permission, not a promise. In practice GCC and Clang perform NRVO at every optimisation level, but you must not write code whose correctness depends on it, and the copy or move constructor must remain accessible.
The one rule to remember is a negative one: do not write return std::move(s);. It casts the named local to an rvalue, which disables NRVO and forces a move where there could have been nothing. You get a real move, which is worse than an elided nothing, for zero benefit. GCC flags it with -Wpessimizing-move, which is on by default with -Wall. The same applies to return std::move(String{});, which defeats the C++17 guarantee.
Going deeperNRVO versus RVO, and why the distinction exists
RVO applies to an unnamed prvalue, which since C++17 has no identity until it is materialized, so there is nothing to elide: the object is simply constructed at its destination. NRVO applies to a named local, a real object with a real address for the whole function. The compiler can still place it in the caller's frame, but proving that is safe needs escape analysis, so the standard keeps NRVO optional and the copy or move must stay accessible.
The practical line: returning a fresh temporary is always free in C++17; returning a named local is usually free in practice but never guaranteed. Write factories to return prvalues where you can, and never reach for std::move to force anything.
Common mistakes and how to fix them
2 min readThe double free. A crash in delete[] or free, printed by glibc as double free detected in tcache 2. Cause: copying an owning class without a deep copy, so two objects share one buffer. Diagnose with AddressSanitizer from M0-S03A. Fix: write the copy operations or delete them (rule of three).
The silent copy instead of a move. A profile shows deep copies where you meant to move, or slow vector growth. Cause: std::move on a const object, a suppressed move, or a missing noexcept. Diagnose with a traced counter. Fix: move a non-const object, and write and mark the move operations.
The pessimizing move. -Wpessimizing-move warnings, or a move trace firing on every factory return. Cause: return std::move(local); disables NRVO. Fix: return the local by name.
The unspecified read. A value that is sometimes empty, sometimes not, depending on the library or compiler. Cause: reading a moved-from object before reassigning it. Fix: reassign before reuse, or let the object go out of scope.
The self-assignment surprise. A crash or corrupted buffer on a = a through an aliasing reference. Cause: a hand-written assignment without the guard. Fix: the guard, or the by-value copy-and-swap form, which is self-assignment safe.
The deleted-move surprise. A compile error about a deleted move, or code that moves by copying. Cause: confusing a suppressed move, which copies silently, with a deleted move, which errors. Fix: provide the move, or delete it explicitly so the fallback is intentional.
The standard says a moved-from object is valid but unspecified. Standard containers happen to empty themselves, but a type you write leaves whatever state its move leaves. Reading size() or a pointer right after a move, without reassigning, is relying on an implementation detail that can change under a different standard library.
On a device with 256 MB of RAM and no swap, a deep copy of a large image or sensor frame is not just slow: it temporarily holds two buffers at once, and that transient peak can push a constrained system into the out-of-memory killer. A move is one pointer change with no second allocation. The same reasoning makes emplace_back worth using in the field, where avoiding a second allocation per element keeps the heap from fragmenting.
Try it
1 min readImplement the String class from this lesson with a deep copy, a noexcept move, and a friend swap, then add static counters and prove with printed output that copying and moving each run exactly when the value categories say they will. Measure copies versus moves in std::vector reallocation with a traced type, and flip the move constructor's noexcept to watch the counter switch from moves to copies. Write a move-only FileHandle with deleted copies and a transferring move, and confirm the compiler rejects any attempt to copy it. The practice pack drills value-category classification, the generation table, and perfect forwarding; the next lesson, M8-S02B, builds on move semantics to design ownership with smart pointers.
Key takeaways
- The compiler's default copy copies every member; for a raw pointer that means two owners of one buffer and a double free.
- The rule of three says a class that owns a resource and writes a destructor needs custom copy too; the rule of five adds the two moves; the rule of zero writes none.
- Value categories drive overload resolution: lvalues bind to const T&, rvalues prefer T&&, so a move runs only on a real rvalue.
- std::move is only a static_cast to an rvalue reference; it moves nothing itself, and moving a const object copies.
- A moved-from object is valid but unspecified: destroy it, or assign it a fresh value, and it works again.
- Mark move operations noexcept; otherwise std::vector copies instead of moves when it reallocates.
- std::forward preserves lvalue/rvalue-ness through templates and powers std::make_unique and emplace_back.
- Since C++17, returning a prvalue is guaranteed elision: the object is built directly in the caller, with no copy or move.
Reflect
- Explain to a colleague, in two sentences: explain what the compiler-generated copy constructor and copy assignment do, and why copying a raw pointer double-frees.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Official docscppreference, Value categories
- Official docscppreference, Copy constructors
- Official docscppreference, Move constructors
- Official docscppreference, Copy elision
- Official docscppreference, std::move
- Official docscppreference, std::forward
- Official docscppreference, Reference declaration
- Official docsC++ Core Guidelines
Official documentation first. Links checked when the lesson was published.