Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 171 ยท Object-Oriented Programming

The Rule of Zero, Three and Five

Learn the C++ rules of zero, three and five - the six special member functions, when the compiler generates them, = default and = delete, and why the rule of zero wins.

You've now seen all the functions that control an object's life: constructors, the destructor, copy operations and move operations. The compiler writes most of them for you, but it follows rules that change as soon as you declare one yourself. Declare a destructor for some logging, and your class quietly stops being movable. Declare a move constructor, and it stops being copyable.

Three short rules of thumb keep you out of trouble. The rule of three and the rule of five say: if a class needs one custom resource-management function, it needs the whole set. The rule of zero says the best number to write is none, because members like std::string, std::vector and std::unique_ptr already manage themselves. In this lesson you'll learn the six special member functions, exactly when the compiler generates each one, how to use = default and = delete to state your intent, and how to design classes that need no special code at all.

The six special member functions

Function Signature Called when
Default constructor T() T x;, T x{};, std::vector<T>(5)
Destructor ~T() the object's lifetime ends
Copy constructor T(const T&) a new object is made from an lvalue T
Copy assignment T& operator=(const T&) an existing object is assigned an lvalue T
Move constructor T(T&&) noexcept a new object is made from an rvalue T
Move assignment T& operator=(T&&) noexcept an existing object is assigned an rvalue T

They're "special" because the compiler can declare and define them implicitly. An implicit version does the obvious memberwise thing: the destructor destroys members in reverse order, the copy constructor copies each member, the move constructor moves each member, and so on.

When the compiler generates them

The rules exist to protect you. If you wrote a custom destructor, the class probably manages a resource, so blindly moving or copying members might be wrong. The compiler reacts by withholding some functions.

You declareโ€ฆ Default ctor Copy ctor / copy assign Move ctor / move assign
nothing generated generated generated
any constructor not declared generated generated
destructor generated generated (deprecated) not declared
copy constructor or copy assignment not declared (only for copy ctor) the other one generated (deprecated) not declared
move constructor or move assignment not declared (only for move ctor) deleted the other one not declared

"Not declared" for moves is the sneaky one. When a class has no move constructor, moving it falls back to copying, because a const T& parameter binds to rvalues too. Nothing fails to compile; your code just gets slower. "Deleted" for copies is loud: once you declare a move operation, copying is a compile error until you declare copies too.

"Deprecated" means the language still generates the function today, but relying on it is considered a bug waiting to happen and may stop working in a future standard. GCC's -Wdeprecated-copy (part of -Wextra) and -Wdeprecated-copy-dtor flag these cases.

The silent-copy trap

Here's the trap in action. Two classes hold the same std::vector. The second has a destructor added "just for logging", which suppresses its move operations:

C++ A destructor silently turns moves into copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::move(w1) compiles, but with no move constructor, the copy constructor runs and duplicates 100,000 integers. The trait at the end confirms the side effect on std::vector growth: since the copy constructor isn't noexcept, the class doesn't count as nothrow-movable, so a vector of them would copy on every reallocation.

Writing ~WithDestructor() = default; instead would have the same effect: what matters is that the destructor is user-declared, not what it does. The fix is to say what you want: add WithDestructor(WithDestructor&&) = default; and the other three, or better, drop the empty destructor entirely.

The rule of three

Before C++11, the rule was: if a class needs a custom destructor, copy constructor or copy assignment operator, it almost certainly needs all three. The reason is that all three exist for the same job, managing a resource the members don't manage themselves. The broken Scores class from Copy Constructors and Copy Assignment had a destructor but compiler-generated copies, and got double frees as a result.

The rule of five

C++11 added two move operations to the set. The rule of five: if you define or = delete any of the destructor, copy constructor, copy assignment, move constructor or move assignment, declare all five. You can implement them, = default them or = delete them, but don't leave any to the generation rules above.

Here's a complete rule-of-five class that owns a simulated operating-system handle (real code would wrap a file descriptor, socket or GPU object in the same way):

C++ A rule-of-five handle class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every handle is closed exactly once, moved-from handles hold -1 and close nothing, and copies get their own handle. That's a lot of careful code for one integer, which is exactly why you should rarely write it.

The rule of zero

The rule of zero: design classes so they need none of the five. Put each resource in its own small owner type (a standard container, a smart pointer, or a one-off RAII class written with the rule of five), then build everything else out of those. The compiler-generated functions are then correct, noexcept where possible, and free of bugs you didn't write.

std::unique_ptr with a custom deleter turns the 50-line Handle into a few lines. Compare the generated behavior with type traits:

C++ Rule of zero with unique_ptr and standard members

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

LogFile is automatically move-only because one member is, Settings is copyable because all its members are, and both have noexcept moves. The handle is closed once, when b is destroyed. (a.handle was moved from; a moved-from unique_ptr is guaranteed null.) You'll see more custom deleters in Smart Pointers: std::unique_ptr.

= default and = delete

Two tools let you state intent instead of relying on the generation rules:

  • = default asks for the compiler's memberwise version explicitly. Use it to bring back a function that was suppressed, or to document that the default is intended.
  • = delete removes a function. Calling it is a compile error with a clear message. It works on any function, not only special members.
C++ Stating intent with default and delete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Deleting set_volume(double) is a nice trick: overload resolution still picks it for a double argument, and then the call is rejected, so nobody can pass 7.5 and get 7.

Polymorphic base classes: the rule of five defaults

A base class meant for inheritance needs a virtual destructor (you'll see why in Virtual Functions and Polymorphism). Declaring that destructor suppresses the implicit moves, and the copies become deprecated. The idiomatic fix is to default all five explicitly:

C++
class Shape {
public:
    virtual ~Shape() = default;
    Shape() = default;
    Shape(const Shape&) = default;
    Shape& operator=(const Shape&) = default;
    Shape(Shape&&) = default;
    Shape& operator=(Shape&&) = default;
    virtual double area() const = 0;
};

Many teams instead make polymorphic bases non-copyable (= delete the copies) to prevent object slicing, and clone through a virtual function when needed.

Choosing a rule

  • Default to the rule of zero. Store resources in std::string, containers, std::unique_ptr, std::shared_ptr, std::optional and other self-managing types.
  • Use the rule of five only in small resource-owning classes whose single job is managing one resource. Make moves noexcept.
  • When you must declare one special member, declare them all, using = default and = delete to make the remaining choices explicit.
  • Don't add an empty destructor. It does nothing useful and costs you moves.
  • Check your assumptions with static_assert(std::is_nothrow_move_constructible_v<T>); for types stored in vectors.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A class has only a user-declared destructor ~Cache() {} plus std::vector members. What happens with Cache b = std::move(a);?

    A user-declared destructor stops the compiler from declaring move operations. The rvalue then binds to the implicit copy constructor's const reference, so the vectors are copied.
  2. 2. A class declares a move constructor and nothing else special. What about copying?

    Declaring a move constructor or move assignment makes the implicit copy operations deleted. Declare them yourself (or = default) if the class should be copyable.
  3. 3. Which class follows the rule of zero?

    The rule of zero means the class writes none of the special members because its members manage their resources. This class is automatically move-only and correct.
  4. 4. What does void send(int); void send(double) = delete; achieve?

    Deleted functions take part in overload resolution. send(2.5) picks the double overload, which is deleted, so the call is an error instead of a silent narrowing conversion.

Summary

  • The six special member functions are the default constructor, destructor, copy constructor, copy assignment, move constructor and move assignment.
  • Declaring any constructor removes the implicit default constructor; declaring a destructor or copy operation removes the implicit moves (which then fall back to copies); declaring a move operation deletes the implicit copies.
  • Rule of three/five: if you write one of the destructor, copy or move operations, declare all five, implementing, defaulting or deleting each.
  • Rule of zero: prefer classes whose members manage themselves, so you write none of them.
  • = default restores or documents the compiler's version; = delete forbids a function, including unwanted overloads.
  • Polymorphic bases need a virtual destructor; default (or delete) the other four explicitly.

Next: Inheritance, where you'll build new classes on top of existing ones.