Skip to content

The Rule of Zero and the Rule of Five

Difficulty: Intermediate

Key concepts

  • special member functions
  • Rule of Zero
  • Rule of Five
  • Rule of Three
  • = default
  • = delete
  • double free
  • custom deleter
  • copy and swap
  • Which special member functions the compiler writes for you, and when it does not.
  • Why a class that manages a resource directly needs all five: the Rule of Five.
  • Why most classes should declare none: the Rule of Zero.
  • How to use = default, = delete, and std::unique_ptr with a custom deleter to stay at zero.

The previous lesson introduced the copy and move operations. Together with the destructor, they are the five special member functions that decide what happens when an object is copied, moved, and destroyed:

IllustrativeA fragment for explanation; not compiled on its own.

class Widget {
public:
~Widget(); // destructor
Widget(const Widget& other); // copy constructor
Widget& operator=(const Widget& other); // copy assignment
Widget(Widget&& other) noexcept; // move constructor
Widget& operator=(Widget&& other) noexcept; // move assignment
};

If you do not declare them, the compiler generates them, and each generated one works member by member: the generated copy constructor copies each member, the generated destructor destroys each member, and so on. Whether that is right depends entirely on the members.

The compiler also stops generating some of them when you declare others. The rules that matter in practice:

If you declare… then the compiler…
nothing generates all five.
a destructor, or either copy operation does not generate the moves. Moving falls back to copying.
either move operation deletes the copies, and does not generate the other move. Declare both moves.
a destructor, or one copy operation still generates the (other) copies, but that is deprecated, and often a bug.

The second row is the subtle one. Adding a destructor “just to log something” silently turns every move of that class into a copy.

The problem: a destructor without the copies

Section titled “The problem: a destructor without the copies”

Here is a class that owns a raw character array:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

double_free.cpp
// FLAWED. A title that keeps its own copy of the characters in an array it
// allocates with new[] and frees with delete[]. The constructor and the
// destructor are each correct; the bug is in the copy the compiler writes.
class Title {
public:
// new char[strlen(text) + 1] allocates room for the characters plus the
// '\0' that ends every C string; strcpy copies them, '\0' included.
explicit Title(const char* text) : text_(new char[std::strlen(text) + 1]) {
std::strcpy(text_, text);
}
// Frees the array. Correct for one owner, but every Title runs it, so
// two Titles holding the same pointer would free the same array twice.
~Title() { delete[] text_; }
// No copy constructor or copy assignment declared, so the compiler
// generates ones that copy the pointer, not the characters.
[[nodiscard]] const char* c_str() const noexcept { return text_; }
private:
char* text_; // owns the array (or is meant to)
};
// Takes a Title by value, so calling it makes a copy, `title`, with the
// generated copy constructor. That copy holds the same address as the
// caller's object, and `title` is destroyed when print returns.
void print(Title title) { std::cout << title.c_str() << '\n'; } // copies
// Where it goes wrong, step by step:
// 1. `original` allocates an array holding "Middlemarch".
// 2. print(original) copies the pointer into `title`: two owners.
// 3. print returns; ~Title for `title` deletes the array.
// 4. original.c_str() now points at freed memory: undefined behaviour.
// 5. demo ends; ~Title for `original` deletes the same array again: a
// double free, also undefined behaviour.
void demo() {
Title original("Middlemarch");
print(original); // the copy's destructor deletes original's array
std::cout << original.c_str() << '\n'; // reads freed memory
} // original's destructor deletes the same array again

The destructor is correct by itself: it releases the array. But the class declares no copy operations, so the compiler generates a copy constructor that copies each member, and the only member is the pointer. During print(original), original and the parameter title hold the same address. When title is destroyed at the end of print, it deletes the array. Then original reads freed memory, and its destructor deletes the same array again: a double free. Both are undefined behaviour. GCC 11 and Clang 14 compile this without a warning under this site’s flags, so it is compiled to show that, and never run.

The generated copy is wrong because the class manages its resource itself: the destructor knows the pointer owns something, but the generated copy does not. That observation gives two possible fixes, and they are the two rules.

If a class needs a user-written destructor, copy constructor, copy assignment, move constructor, or move assignment, it almost certainly needs to decide all five.

(Before C++11 had moves, this was the Rule of Three: destructor, copy constructor, copy assignment.) “Decide” means each one is written, defaulted, or deleted on purpose; none is left to the generation rules by accident.

A class that wraps a C library handle is the honest case for the Rule of Five. Here is a small stand-in for such a library, which also counts how many handles are open so tests can check for leaks:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection_api.hpp
// A C-style interface: plain functions and raw pointers, with no
// destructors to help. Each handle from connection_open or
// connection_duplicate must be passed to connection_close exactly once.
// Connection is only declared, never defined here, so callers can hold
// a Connection* but cannot look inside one.
//
// Returns nullptr if address is empty.
Connection* connection_open(const char* address);
// Returns a new handle to the same address, or nullptr if out of resources.
// (This stand-in only returns nullptr when `connection` is null.)
Connection* connection_duplicate(const Connection* connection);
// Releases a handle. Passing nullptr does nothing.
void connection_close(Connection* connection);
// The address the connection was opened with. Requires a non-null handle.
const char* connection_address(const Connection* connection);

ConnectionHandle owns one connection and decides what each of the five means:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

handle.hpp
// Invariant: conn_ is an open connection owned by this object, or nullptr
// after this object has been moved from. A moved-from handle may be
// destroyed, assigned to, copied (giving another empty handle), or asked
// valid(); nothing else.
// Wraps one connection from the C-style API above, so that the C++ rules
// for copying, moving, and destroying an object do the right thing to it.
// All five special members are declared here and defined in handle.cpp.
class ConnectionHandle {
public:
// Throws std::runtime_error if the connection cannot be opened.
explicit ConnectionHandle(const std::string& address);
~ConnectionHandle(); // closes the connection, if there is one
// Copying makes a second, independent connection to the same address,
// so each handle closes only its own.
ConnectionHandle(const ConnectionHandle& other); // duplicates
ConnectionHandle& operator=(const ConnectionHandle& other); // duplicates
// Moving hands the one connection over and leaves the source null.
ConnectionHandle(ConnectionHandle&& other) noexcept; // takes over
ConnectionHandle& operator=(ConnectionHandle&& other) noexcept;
[[nodiscard]] bool valid() const noexcept { return conn_ != nullptr; }
// Requires valid().
[[nodiscard]] std::string address() const;
// Exchanges the two handles' pointers: each object ends up owning what
// the other owned. Nothing is opened or closed, so it cannot fail.
void swap(ConnectionHandle& other) noexcept { std::swap(conn_, other.conn_); }
private:
api::Connection* conn_; // owned: this object must close it
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

handle.cpp
// open_or_throw and duplicate_or_throw are small helpers defined just above:
// they call connection_open or connection_duplicate and throw
// std::runtime_error if the library returns nullptr. duplicate_or_throw
// returns nullptr, without throwing, when it is given nullptr.
// Opens the connection, or throws so that no handle without one exists.
ConnectionHandle::ConnectionHandle(const std::string& address) : conn_(open_or_throw(address)) {}
// Destructor: close what this handle owns. connection_close(nullptr) does
// nothing, so a moved-from handle is destroyed safely.
ConnectionHandle::~ConnectionHandle() { api::connection_close(conn_); } // null-safe
// Copy constructor: ask the library for a second, independent connection.
// Copying a moved-from handle (null) gives another null handle.
ConnectionHandle::ConnectionHandle(const ConnectionHandle& other)
: conn_(duplicate_or_throw(other.conn_)) {}
// Copy and swap: build the copy first (which may throw, leaving *this
// unchanged), then swap it in. The old connection is closed when `copy`
// is destroyed. Self-assignment is safe, if wasteful.
ConnectionHandle& ConnectionHandle::operator=(const ConnectionHandle& other) {
ConnectionHandle copy(other); // the risky step: may throw
swap(copy); // cannot throw: *this gets the duplicate
return *this;
} // `copy` now holds our old connection, and its destructor closes it
// Move constructor: std::exchange returns other.conn_ and sets it to
// nullptr in one step, so the connection now has exactly one owner, this
// object. No library call, so nothing can fail.
ConnectionHandle::ConnectionHandle(ConnectionHandle&& other) noexcept
: conn_(std::exchange(other.conn_, nullptr)) {}
// Move assignment: this handle may already own a connection, so it closes
// that first and then takes over other's. `this != &other` compares the
// two objects' addresses: for a = std::move(a) they are the same, and
// skipping the body keeps a from closing its own connection.
ConnectionHandle& ConnectionHandle::operator=(ConnectionHandle&& other) noexcept {
if (this != &other) {
api::connection_close(conn_); // release what we own
conn_ = std::exchange(other.conn_, nullptr); // take over theirs
}
return *this;
}
How this code works: the two ConnectionHandle assignments

Assignment is the hard case, because the object on the left already owns a connection that must be closed, and the one on the right must not be harmed.

Copy assignment, b = a;, where a owns connection “one” and b owns “two”. Count the open connections, as the first test does (a third handle c also holds a duplicate of “one”, so the count starts at 3):

Step b owns copy owns Open
before “two” (not created) 3
ConnectionHandle copy(other); “two” new “one” 4
swap(copy); new “one” “two” 4
return *this;, then copy destroyed new “one” (closed) 3

If connection_duplicate had failed in the first step, it would have thrown before b was touched: b would still own “two”. The same steps make a = a safe: the duplicate is made from a before anything of a’s is closed, so it only costs one extra open and close.

Move assignment, c = std::move(b); (c owns a duplicate of “one”, b owns another):

  1. this != &other: they are different objects, so the body runs.
  2. connection_close(conn_) closes c’s own connection. Open goes from 3 to 2.
  3. conn_ = std::exchange(other.conn_, nullptr) makes c own b’s connection and leaves b null, so b.valid() is now false.
  4. Later, b’s destructor calls connection_close(nullptr), which does nothing, and c’s closes the connection it took over. Each connection is closed once.

Without the self-check, a = std::move(a) would run step 2 on a’s own connection and then, in step 3, take back the pointer it had just closed.

  • Destructor: closes the connection. connection_close(nullptr) does nothing, so a moved-from handle is safe to destroy.
  • Copy constructor: a copy must own its own connection, so it calls connection_duplicate. Copying the pointer would recreate the double free.
  • Copy assignment, by copy and swap: build the new copy first, then swap it with *this. If duplicating throws, *this has not been touched. The old connection ends up in copy, which closes it when it is destroyed. This one pattern also handles self-assignment (a = a through an alias) correctly, though it makes and discards a needless duplicate.
  • Move constructor: takes the pointer and leaves nullptr behind, using std::exchange. No library call, so it cannot fail: noexcept. Move assignment calls connection_close, which does not throw (a C-style API like this one reports problems through return values, not C++ exceptions), so it is noexcept too.
  • Move assignment: closes what it owns, then takes over. The self-check matters here: without it, a = std::move(a) would close a’s connection and then keep the dangling pointer.

The moved-from state is part of the invariant (“or nullptr after this object has been moved from”), and the header says what may be done with such an object. Supporting moves on a class that owns a resource adds this state, and every member function must respect it: here address() documents that it requires valid().

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// open_connections() asks the stand-in library how many connections are
// open right now, so each line shows what the statement above it did.
// main set std::boolalpha before this snippet, so bools print as words.
{
ConnectionHandle primary("db.library.local");
std::cout << "after open: " << open_connections() << " open\n";
ConnectionHandle copy = primary; // duplicates: a second connection
std::cout << "after copy: " << open_connections() << " open, same address: "
<< (copy.address() == primary.address()) << '\n';
// primary is left null, so primary.valid() is false.
ConnectionHandle moved = std::move(primary); // takes over: no new connection
std::cout << "after move: " << open_connections() << " open, primary valid: "
<< primary.valid() << '\n';
// Session{"ada", moved} fills the two members in order. `moved` is a
// named object, so the connection member is copy-constructed from
// it: the open count rises to 3.
Session session{"ada", moved}; // Rule of Zero: copying the member duplicates
std::cout << "in session: " << open_connections() << " open\n";
} // session, moved, copy, primary destroyed: three closes, primary had none
std::cout << "after scope: " << open_connections() << " open\n";
{
// `unique` is a UniqueConnection; its deleter closes the connection
// when the block ends.
auto unique = lld::rule5::open_unique("cache.library.local");
std::cout << "unique: " << open_connections() << " open\n";
}
std::cout << "after scope: " << open_connections() << " open\n";
Expected output
after open: 1 open
after copy: 2 open, same address: true
after move: 2 open, primary valid: false
in session: 3 open
after scope: 0 open
unique: 1 open
after scope: 0 open

That is a lot of careful code, around 30 lines, for one pointer. Each line is a chance for a mistake, which is why the next rule is the default.

Classes that are not specifically about managing a resource should declare none of the five.

Instead, make every member manage itself. Then the generated special members, which work member by member, are automatically correct.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

handle.hpp
// Rule of Zero, part 1: a class whose members manage themselves declares no
// special members. Copying a Session copies the name and duplicates the
// connection; moving it moves both; destroying it closes the connection.
struct Session {
std::string user;
ConnectionHandle connection;
};
// Rule of Zero, part 2: when the resource should not be copied at all,
// std::unique_ptr with a custom deleter does all the work. The class is
// automatically move-only.
// A deleter: a tiny type with an operator(), so an object of it can be
// called like a function. unique_ptr calls it with the pointer it owns
// when it would otherwise use `delete`.
struct CloseConnection {
void operator()(api::Connection* connection) const noexcept {
api::connection_close(connection);
}
};
// `using` gives the long type a short name. The second template argument
// tells unique_ptr to release with CloseConnection instead of delete.
using UniqueConnection = std::unique_ptr<api::Connection, CloseConnection>;
// Returns an owner that closes the connection when it is destroyed.
// Throws std::runtime_error if the connection cannot be opened.
UniqueConnection open_unique(const std::string& address);
  • Session declares nothing. Copying a Session copies the std::string and copies the ConnectionHandle, which duplicates the connection; moving moves both; destroying it closes the connection. The output above shows the open count rise to 3 when session is created from moved. The resource-management code exists once, in ConnectionHandle, and every class that contains one benefits.
  • UniqueConnection is std::unique_ptr with a custom deleter: a small function object that unique_ptr calls instead of delete. It needs no class of its own at all. Because unique_ptr cannot be copied, neither can anything that contains one (unless it writes its own copy operations), so a connection that should never be duplicated is protected for free.

The Title class from the flawed example needs no rule of five either: holding the text in a std::string instead of a char* makes all five generated operations correct, and the class shrinks to a constructor and an accessor.

The same technique makes the RAII lesson’s File movable:

IllustrativeA fragment for explanation; not compiled on its own.

// The deleter: unique_ptr calls CloseFile{}(handle) instead of delete.
// unique_ptr only calls its deleter when it holds a non-null pointer.
struct CloseFile {
void operator()(std::FILE* file) const noexcept { std::fclose(file); }
};
// Invariant: handle_ is open, or null after this File has been moved from.
class File {
public:
File(const std::filesystem::path& path, const char* mode); // throws on failure
void write(std::string_view text); // requires an open handle
[[nodiscard]] std::string read_all();
private:
// Owns the FILE* and closes it with CloseFile; moving the File moves
// this pointer and leaves the source null.
std::unique_ptr<std::FILE, CloseFile> handle_;
};

No destructor and no copy or move declarations: the generated destructor closes the file, the generated copies are deleted (because unique_ptr’s are), and the generated moves transfer the handle. Note that the invariant changed: a movable File has a moved-from state, which the comment must now admit.

Sometimes you must declare a special member for another reason, and you want the generated behaviour anyway. = default asks for the generated version explicitly; = delete forbids an operation.

The common case is a base class used through pointers, which needs a virtual destructor (see the smart pointers lesson). Declaring that destructor stops the moves from being generated, and copying a polymorphic object risks slicing (see the value semantics lesson). So a base class usually decides all five in one go:

IllustrativeA fragment for explanation; not compiled on its own.

class FeePolicy {
public:
// Virtual, so deleting a derived object through a FeePolicy pointer runs
// the derived destructor. `= default`: the generated body is right.
virtual ~FeePolicy() = default;
[[nodiscard]] virtual int fee_for(int days_late) const = 0;
// protected: usable by derived classes (their constructors call
// FeePolicy()), but not by outside code.
protected:
// Neither this class nor any derived class can be copied or moved, so
// nothing can be sliced.
FeePolicy() = default;
FeePolicy(const FeePolicy&) = delete;
FeePolicy& operator=(const FeePolicy&) = delete;
FeePolicy(FeePolicy&&) = delete;
FeePolicy& operator=(FeePolicy&&) = delete;
};

This is still in the spirit of the Rule of Zero: no special member has a hand-written body. Making all five explicit costs a few lines and leaves no doubt about what the class supports. (Deleting the copy operations is enough on its own to suppress the moves; deleting the moves too says so directly.) If derived classes need to be copyable, declare the base’s copy operations protected and = default instead: derived classes can then use them, but outside code cannot copy a FeePolicy out of a derived object.

Resource bugs in special members rarely show up as wrong output; they show up as leaks, double releases, and crashes later. So the tests count open connections after every combination of copies, moves, assignments, self-assignment, and a failed open, and check that the count returns to zero when the objects are gone. The AddressSanitizer build also runs them; it detects leaks and double frees of the memory the stand-in library allocates.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_handle.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) fails it if the
// condition is false, LLD_CHECK_EQ(actual, expected) fails it if the values
// differ, and LLD_CHECK_THROWS(expression, type) fails it unless the
// expression throws that exception type. Most tests work inside an inner
// block and then check that open_connections() is back to 0, which proves
// every connection was closed exactly once.
// A mix of copy, copy assignment, self-assignment, and move assignment.
LLD_TEST(copies_and_assignments_close_every_connection_once) {
{
ConnectionHandle a("one");
ConnectionHandle b("two");
ConnectionHandle c = a; // 3 open
// Copy and swap: a fourth connection is opened for the duplicate,
// then b's old "two" is closed when the temporary copy dies.
b = a; // closes "two", duplicates "one": still 3
LLD_CHECK_EQ(open_connections(), 3);
LLD_CHECK_EQ(b.address(), std::string("one"));
// `alias` is another name for `a`, so this assigns a to itself.
ConnectionHandle& alias = a;
a = alias; // self-assignment (through an alias) is safe
LLD_CHECK_EQ(open_connections(), 3);
c = std::move(b); // closes c's, takes b's: 2 open
LLD_CHECK_EQ(open_connections(), 2);
LLD_CHECK(!b.valid());
}
LLD_CHECK_EQ(open_connections(), 0);
}
// The moved-from state is usable in the ways the header promises.
LLD_TEST(a_moved_from_handle_can_be_copied_and_reassigned) {
{
ConnectionHandle a("one");
ConnectionHandle b = std::move(a);
ConnectionHandle empty = a; // copying a moved-from handle gives another empty one
LLD_CHECK(!empty.valid());
// Move assignment from a temporary: a closes nothing (it is null)
// and takes over the new connection. Open now: b's and a's.
a = ConnectionHandle("again");
LLD_CHECK(a.valid());
LLD_CHECK_EQ(open_connections(), 2);
}
LLD_CHECK_EQ(open_connections(), 0);
}
// An empty address makes connection_open return nullptr, so the
// constructor throws, and nothing was opened that would need closing.
LLD_TEST(a_failed_open_throws_and_leaks_nothing) {
LLD_CHECK_THROWS(ConnectionHandle(""), std::runtime_error);
LLD_CHECK_EQ(open_connections(), 0);
}
// The Rule-of-Zero types get the right operations without declaring any.
LLD_TEST(rule_of_zero_types_get_correct_special_members) {
// static_assert is checked when the file compiles. The std::is_..._v
// names are compile-time yes/no questions about a type: "can it be
// moved without throwing?", "can it be copied?".
static_assert(std::is_nothrow_move_constructible_v<ConnectionHandle>);
static_assert(std::is_copy_constructible_v<Session>);
static_assert(!std::is_copy_constructible_v<UniqueConnection>);
{
std::vector<Session> sessions;
// The temporary Session is moved into the vector: 1 open.
sessions.push_back(Session{"ada", ConnectionHandle("one")});
// front() is the first element; pushing it copies the Session,
// whose generated copy duplicates the connection: 2 open.
sessions.push_back(sessions.front()); // copies, so duplicates
LLD_CHECK_EQ(open_connections(), 2);
// Moving a unique_ptr transfers the one connection: still 3, not 4.
UniqueConnection unique = lld::rule5::open_unique("two");
UniqueConnection taken = std::move(unique);
LLD_CHECK_EQ(open_connections(), 3);
}
LLD_CHECK_EQ(open_connections(), 0);
}
// The exercise answer: the generated copy duplicates the vector, so adding
// to the copy leaves the original with its one name.
LLD_TEST(roster_copies_are_independent) {
Roster original;
original.add("Ada");
Roster copy = original;
copy.add("Grace");
LLD_CHECK_EQ(original.size(), std::size_t{1});
LLD_CHECK_EQ(copy.at(1), std::string("Grace"));
Roster moved = std::move(copy);
LLD_CHECK_EQ(moved.size(), std::size_t{2});
}

The static_assert lines check which operations each type supports at compile time: the handle’s move must be noexcept, a Session must be copyable, and a UniqueConnection must not be.

  • Rule of Zero (the default): for almost every class. Hold resources through standard types (std::string, std::vector, std::unique_ptr, std::shared_ptr) or through your own resource-managing class.
  • Rule of Zero with unique_ptr and a custom deleter: for a C handle that should have exactly one owner and needs only a release function.
  • Rule of Five: only in a small class whose single job is managing one resource, when the standard types cannot express it, for example a handle that must be duplicated with a library call when copied. Keep such a class tiny, test it hard, and build everything else from it.
  • All five = default or = delete: when you need to declare one of them (such as a virtual destructor) and want the class’s copy and move behaviour stated explicitly.
  • A destructor without copy operations, for a class that owns a raw pointer: double free.
  • Adding a destructor to a class that was fine without one, for example for logging. It silently turns moves into copies.
  • Copy assignment that releases first and copies second. If the copy throws, the object is left holding a released resource. Use copy and swap, or copy into locals first.
  • Move assignment without a self-check, when it releases before taking over.
  • Forgetting the moved-from state. Every member function must say whether it works on a moved-from object.
  • Writing the five for a class that could hold a std::unique_ptr or a std::vector instead.

New requirement: “Connections are expensive. Copying a session should share its connection instead of opening a new one.”

Under the Rule of Zero, this is a change of member type, not of special members. Change Session::connection to std::shared_ptr<const ConnectionHandle> (or a std::shared_ptr<api::Connection> with a deleter that closes it). Copying a Session now copies the shared_ptr, so both sessions share the one connection, and it is closed when the last session is destroyed. Session still declares no special members. The trade-off is the one from the smart pointers lesson: shared ownership makes it harder to say when the connection closes, and if the connection holds state that sessions change, they now affect each other, so the sharing must be documented.

Exercise: Refactor a Rule-of-Five class to the Rule of Zero

This Roster manages its own array of names. It is correct, as far as anyone has checked, but long:

IllustrativeA fragment for explanation; not compiled on its own.

// Owns a heap array of size_ strings through the raw pointer names_
// (nullptr when empty), so it must decide all five special members.
class Roster {
public:
Roster() = default;
~Roster() { delete[] names_; } // delete[] of nullptr does nothing
// Copy: allocate a new array of the same size (none if empty), then copy
// each string into it; names_ + size_ is one past the last element.
Roster(const Roster& other)
: names_(other.size_ ? new std::string[other.size_] : nullptr), size_(other.size_) {
std::copy(other.names_, other.names_ + size_, names_);
}
// Copy and swap, as in ConnectionHandle: copy first, then swap both
// members; `copy` deletes the old array when it is destroyed.
Roster& operator=(const Roster& other) {
Roster copy(other);
std::swap(names_, copy.names_);
std::swap(size_, copy.size_);
return *this;
}
// Move: take the pointer and size, leave other empty (nullptr, 0).
Roster(Roster&& other) noexcept
: names_(std::exchange(other.names_, nullptr)), size_(std::exchange(other.size_, 0)) {}
// Move assignment: free our array, then take over other's.
Roster& operator=(Roster&& other) noexcept {
if (this != &other) {
delete[] names_;
names_ = std::exchange(other.names_, nullptr);
size_ = std::exchange(other.size_, 0);
}
return *this;
}
// Adds one name: allocate an array one longer, move the old names into
// it (this std::move, with three arguments, moves a whole range), put
// the new name last, free the old array, and keep the new one.
void add(std::string name) {
auto* bigger = new std::string[size_ + 1];
std::move(names_, names_ + size_, bigger);
bigger[size_] = std::move(name);
delete[] names_;
names_ = bigger;
++size_;
}
[[nodiscard]] std::size_t size() const noexcept { return size_; }
[[nodiscard]] const std::string& at(std::size_t index) const; // throws if out of range
private:
std::string* names_ = nullptr;
std::size_t size_ = 0;
};
  1. Rewrite it to follow the Rule of Zero, keeping the public interface.
  2. List the bugs and costs that disappear.
Show the explained answer
  1. Hold the names in a std::vector<std::string>. This version is compiled and tested with this page’s examples (roster_copies_are_independent above):

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

roster.hpp
// No destructor, no copy or move operations: std::vector and std::string
// already copy, move, and release correctly, so the defaults do too.
class Roster {
public:
// By value, then moved into the vector: one copy at most, made by the
// caller only if they pass a named string.
void add(std::string name) { names_.push_back(std::move(name)); }
[[nodiscard]] std::size_t size() const noexcept { return names_.size(); }
// Throws std::out_of_range if index >= size().
[[nodiscard]] const std::string& at(std::size_t index) const { return names_.at(index); }
private:
std::vector<std::string> names_;
};
  1. What disappears:
    • All five special members, and the chance of getting one wrong or forgetting one, as Title did.
    • The cost of add. The original reallocates and moves every name on every call, so adding n names does about n²/2 moves (and default-constructs a whole new array of strings each time). std::vector grows its capacity geometrically, so adding is cheap on average.
    • A hidden exception-safety assumption. The original add is safe only because nothing after the new can throw: moving a std::string does not. If the element type’s moves could throw, bigger would leak and the roster would be half-moved. std::vector::push_back handles this itself (with the strong guarantee when the element’s moves are noexcept or it is copyable).
    • at needs no hand-written bounds check: std::vector::at throws std::out_of_range itself.

The generated special members of the new Roster are correct because every member, here just one, already has correct ones.

  • The five special members are the destructor, copy constructor, copy assignment, move constructor, and move assignment. The generated ones work member by member.
  • Declaring a destructor or a copy operation stops the moves from being generated; declaring a move operation deletes the copies.
  • Rule of Five: a class that manages a resource directly must decide all five, including what a moved-from object is.
  • Rule of Zero: every other class declares none, holding its resources in members that manage themselves; std::unique_ptr with a custom deleter covers most C handles.
  • Use = default and = delete to state the five explicitly when you must declare one of them, such as a virtual destructor.