Should a C++ codebase make the rule of zero its default policy, and how would you handle the classes that cannot follow it?
answer
- ownership lives in members
- few audited resource types
- polymorphic bases need care
- pimpl and out-of-line destructors
- check it with traits and warnings
basics
~20 sYes, as the default: classes hold resources only through members that already manage them, so the compiler writes correct copies, moves and destructors. The exceptions, resource wrappers, polymorphic bases and out-of-line destructors, declare or delete all five and are reviewed deliberately.
solid answer
~50 sThe rule of zero says a class that does not exist to manage a resource declares none of the five copy, move and destructor members, holding resources through `std::vector`, `std::string`, `std::unique_ptr` or a project RAII handle. In the `Image` refactor, replacing `unsigned char* pixels_` with `std::vector<unsigned char>` deletes the destructor and both copies and gains `noexcept` moves, and resource logic moves into a few audited wrapper types. The exceptions need rules of their own: wrapper types follow the rule of five; a polymorphic base needs a virtual destructor, which suppresses moves, so declare all five as defaulted, often `protected` to prevent slicing; a pimpl or ABI-stable class must define its destructor out of line, so it declares the moves too. Trade-offs to state: `unique_ptr` members make types move-only, `shared_ptr` members silently turn copies into shared state, and enforcement needs static assertions and warnings such as GCC's `-Wdeprecated-copy-dtor`, which neither `-Wall` nor `-Wextra` enables.
code
cpp · 27 lines#include <cstddef>
#include <cstdio>
#include <type_traits>
#include <utility>
#include <vector>
class Image { // rule of zero: no special members declared
public:
Image(std::size_t w, std::size_t h) : width_(w), height_(h), pixels_(w * h) {}
std::size_t width() const { return width_; }
std::size_t height() const { return height_; }
unsigned char& at(std::size_t x, std::size_t y) { return pixels_[y * width_ + x]; }
private:
std::size_t width_, height_;
std::vector<unsigned char> pixels_; // the member owns the buffer
};
static_assert(std::is_nothrow_move_constructible_v<Image>);
int main() {
Image a(640, 480);
a.at(1, 1) = 255;
Image b = a; // deep copy, generated by the compiler
Image c = std::move(a); // cheap move, also generated
b.at(1, 1) = 7;
std::printf("%d %d %zux%zu\n", c.at(1, 1), b.at(1, 1), c.width(), c.height());
}go deeper
Recall that the rule of zero means letting members such as std::vector and std::unique_ptr own resources, so the class declares no copy, move or destructor.
Explain how the generated members compose from the members' own, and why a std::vector member gives Image correct copies and noexcept moves.
Handle the exceptions correctly: polymorphic bases with five defaulted members, pimpl classes with out-of-line destructor and moves, and resource wrappers with the rule of five.
Own the policy: define the exception list, the warnings and static assertions that enforce it, and the review rule of zero or five, and weigh ABI and semantic changes when migrating.
## The policy The **rule of zero** is the guideline that a class whose job is not resource management should declare **none** of the destructor, copy constructor, copy assignment, move constructor and move assignment. Resources are held through members whose types already have correct special members, and the compiler composes the class's members from theirs. As a codebase policy it reads: - Domain types hold memory in `std::vector` or `std::string`, single ownership in `std::unique_ptr`, shared ownership in `std::shared_ptr`, and OS handles in a small project RAII type. - Only those RAII types write special members, and they follow the **rule of five**. - Every other class declares none of the five, unless it falls into a documented exception below. ## What the Image refactor buys The rule-of-three `Image` owned `unsigned char* pixels_` and hand-wrote a destructor, a copy constructor and a copy assignment. Replacing the pointer with `std::vector<unsigned char> pixels_` lets all three go: | Concern | Rule-of-three Image | Rule-of-zero Image | |---|---|---| | Lines of special-member code | three functions to keep in sync | none | | Move support | none, since the destructor suppressed it | implicit and `noexcept` | | Copy assignment | allocates every time unless hand-optimised | `std::vector`'s copy assignment, which can reuse capacity | | Exception safety of copies | whatever the author wrote | the member's guarantees composed | | Behaviour in `std::vector<Image>` growth | copies | moves | The code example compiles with `static_assert(std::is_nothrow_move_constructible_v<Image>)` and shows a deep copy and a move both generated by the compiler. ## The classes that cannot follow it A policy is only as good as its exceptions, and four come up in every large codebase: 1. **The resource wrappers themselves.** A type wrapping a file descriptor, a GPU texture or a C library handle has to write the destructor and decide copy and move behaviour: usually move-only, with deleted copies and `noexcept` moves. Keep these few, small and heavily reviewed; how to write them is the subject of RAII wrappers. 2. **Polymorphic base classes.** A base used through pointers needs `virtual ~Shape() = default;`. That destructor is user-declared, so the implicit moves disappear and the implicit copies become deprecated. Declare all five as `= default`, and consider making the copy and move operations `protected` so callers cannot slice a derived object through a base reference. 3. **Out-of-line destructors.** A pimpl class holding `std::unique_ptr<Impl>` must declare its destructor in the header and define it, even as `= default`, in the source file where `Impl` is complete. That user-declared destructor suppresses the moves, so the class must declare and out-of-line-default its moves as well. The same applies to any class whose special members are kept out of line for ABI stability. 4. **Types with non-movable members**, such as a `std::mutex`. Their implicit copy and move operations are deleted; either accept that, or write the five explicitly with locking. ## Trade-offs a lead should state - **Member choice changes semantics.** A `std::unique_ptr` member makes the class move-only; a deep copy then needs hand-written copy operations, reopening the rule of five. A `std::shared_ptr` member compiles happily but makes copies **share** state, which is a behaviour change, not a refactor. - **Size and layout.** A `std::vector` member carries a capacity and is larger than a raw pointer; in libc++ it is three pointers. That is an implementation's choice, and it rarely matters outside very small, very numerous objects. - **ABI.** Changing a public class's special members from hand-written to implicit changes whether they are trivial and where they are emitted, which matters for libraries with a stable binary interface. ## Enforcing it No compiler enforces the rule of zero, so a policy needs checks: - Turn on the deprecation warnings for implicit copies: Clang's `-Wdeprecated-copy-with-dtor` and `-Wdeprecated-copy`, GCC's `-Wdeprecated-copy-dtor` and `-Wdeprecated-copy`. GCC enables `-Wdeprecated-copy` with `-Wextra` but not the destructor variant, and Clang's destructor variant sits only in `-Wdeprecated`. - Put `static_assert(std::is_nothrow_move_constructible_v<T>)` next to value types used in containers, so a stray destructor fails the build. - Make the review rule mechanical: a class declares **none** of the five, or it declares or deletes **all** five and carries a comment saying which exception applies. ## How to answer Say yes as a default, give the payoff in the `Image` refactor, list the exceptions with the rule each one follows, and finish with how you would enforce it without slowing the team down.
- In C++, why does a pimpl class with a std::unique_ptr<Impl> member break the rule of zero?`std::unique_ptr<Impl>`'s destructor needs `Impl` to be complete, but the header only forward-declares it. So the class declares `~Widget();` in the header and defines it as `= default` in the source file. That user-declared destructor suppresses the implicit moves, so the class must also declare its move operations and default them in the source file.
- How should a C++ polymorphic base class declare its special members under a rule-of-zero policy?It needs `virtual ~Base() = default;`, which counts as user-declared, so declare the other four explicitly as `= default` rather than relying on deprecated implicit copies and missing moves. Making the copy and move operations `protected` lets derived classes use them while stopping callers from slicing a derived object through a `Base&`.
- The rule of zero means classes never need destructors anywhere in the codebase.
- Replacing a raw pointer with std::shared_ptr is a behaviour-preserving rule-of-zero refactor.
- A virtual destructor = default keeps the implicit move operations.
- The compiler warns by default whenever a class breaks the rule of zero.
- A std::unique_ptr member keeps the class copyable.