skip to content

Rule of Zero/Three/Five

The compiler may generate a destructor, copy and move operations, and declaring one suppresses others. Interviewers ask when to write all five and why zero is the goal.

on this pageshow

explore

questions

5

In C++, what is the rule of three, and what goes wrong when an Image class owning a raw pixel buffer defines only a destructor?

level: juniorimportance: must knowfreq 78%

answer

  1. destructor, copy constructor, copy assignment
  2. the implicit copy is member-wise
  3. two owners, one buffer
  4. double delete[] at scope exit

basics

~20 s

If a class needs a custom destructor, copy constructor or copy assignment, it almost certainly needs all three. An Image with only a destructor gets generated copies that duplicate the pointer, so two Images free one buffer: undefined behaviour.

solid answer

~50 s

The rule of three says the destructor, copy constructor and copy assignment operator travel together: needing one usually means the class manages a resource, and then all three must agree on how. The compiler-generated copy operations copy each member, so for `unsigned char* pixels_` they copy the **pointer**, not the pixels. After `Image b = a;` both objects point at one buffer: writing through `b` changes `a`, and when both go out of scope the destructor runs `delete[]` on the same pointer twice. That is undefined behaviour; AddressSanitizer reports `attempting double-free`. Copy assignment adds a leak, because `a = b` overwrites `a`'s pointer without freeing its old buffer. The fix is to write a deep-copying copy constructor and a copy assignment that frees the old buffer safely, or better, to hold the pixels in a `std::vector<unsigned char>` so the class needs none of the three.

code

cpp · 20 lines
cpp
#include <cstddef>
#include <cstdio>

class Image {
public:
    Image(std::size_t w, std::size_t h)
        : width_(w), height_(h), pixels_(new unsigned char[w * h]{}) {}
    ~Image() { delete[] pixels_; }
    // No copy constructor or copy assignment: the implicit ones copy the pointer.
    std::size_t size() const { return width_ * height_; }
private:
    std::size_t width_, height_;
    unsigned char* pixels_;
};

int main() {
    Image a(640, 480);
    Image b = a;            // shallow copy: a and b own the same buffer
    std::printf("%zu\n", b.size());
}                           // b's destructor frees the buffer, then a's frees it again

go deeper

for a junior

Recall the three members, destructor, copy constructor and copy assignment, and that the generated copies copy a raw pointer, not what it points to.

for a middle

Walk through the double free and the assignment leak step by step, and explain why the C++11 move operations extend the rule to five.

for a senior

Catch rule-of-three violations with -Wdeprecated-copy-with-dtor and AddressSanitizer, and prefer moving ownership into a member over hand-written copies.

for a principal

Treat every hand-written destructor as a review flag, and steer a codebase toward the rule of zero so resource handling lives in a few audited types.

## The three operations C++ classes have **special member functions** that the compiler may declare and define on your behalf. Three of them decide what happens to a resource the class owns: | Special member | Runs when | Compiler-generated version | |---|---|---| | **Destructor** `~Image()` | an object's lifetime ends | destroys each member | | **Copy constructor** `Image(const Image&)` | a new object is made from an existing one | copies each member | | **Copy assignment** `Image& operator=(const Image&)` | an existing object is overwritten | assigns each member | The **rule of three** is the guideline that if a class needs a user-written version of any one of these, it almost certainly needs all three. The reasoning: a custom destructor means the class releases something, such as memory, a file handle or a lock, and the generated copy operations know nothing about that resource. ## What goes wrong with only a destructor The code example's `Image` allocates its pixels with `new unsigned char[w * h]{}` and frees them in `~Image()` with `delete[]`. It declares no copy operations, so the compiler generates them, and they copy the **pointer value**: 1. `Image b = a;` copies `width_`, `height_` and `pixels_`, so `a.pixels_ == b.pixels_`. 2. Both objects now believe they own the buffer. A write through `b` is visible through `a`. 3. At the end of `main`, `b` is destroyed first and frees the buffer; then `a` is destroyed and frees it again. Freeing the same memory twice is **undefined behaviour**. It may appear to work, corrupt the allocator's bookkeeping and crash later, or abort immediately. Built with `-fsanitize=address`, the program stops with a precise report: ```plaintext ERROR: AddressSanitizer: attempting double-free on 0x000104a0c800 in thread T0: #1 0x0001040d4ee4 in Image::~Image() three.cpp:8 #3 0x0001040d4a8c in main three.cpp:20 ``` Copy assignment fails differently. `a = c;` overwrites `a.pixels_` with `c.pixels_`, so `a`'s original buffer is never freed (a **leak**), and `a` and `c` now share one buffer and will double-free it later. ## Fixing it within the rule of three Writing the three by hand looks like this: - The **copy constructor** allocates a new buffer of the same size and copies the pixels into it. - The **copy assignment** must free the old buffer, allocate and copy the new one, and survive `a = a;` without freeing the buffer it is about to copy from. Allocating the new buffer before freeing the old one handles both self-assignment and an allocation failure. - The **destructor** stays as it was. The copy-and-swap idiom is a compact way to get the assignment right, and `= delete` is the answer when copying should not be possible at all. ## Rule of five and rule of zero C++11 added two more special members, the **move constructor** and **move assignment operator**, giving the **rule of five**: a class that manages a resource should consider all five, because a user-declared destructor or copy operation stops the compiler from declaring the moves. The better modern answer is the **rule of zero**: let a member such as `std::vector<unsigned char>` own the pixels. Then the generated destructor, copies and moves all do the right thing, and `Image` declares none of them. ## Spotting the problem early - Clang flags the generated copy with `-Wdeprecated-copy-with-dtor`: `definition of implicit copy constructor for 'Image' is deprecated because it has a user-provided destructor`. The C++ standard deprecates that implicit copy, so the warning points straight at classes that break the rule of three. - AddressSanitizer catches the double free at run time. - In review, a destructor that calls `delete`, `delete[]`, `free` or a close function is the cue to look for the copy operations. ## Where the rule shows up in real code The same shape appears wherever a class releases something in its destructor: - a class that calls `fclose` on a `FILE*` member, where a copy closes the file twice; - a class holding a socket or file descriptor, where a copy closes a descriptor that another object, or by then another connection, is using; - a class that unlocks a mutex in its destructor, where a copy unlocks twice; - a class registering `this` with an observer list, where a copy is never registered or is unregistered twice. In each case, deciding what a copy should mean, deep copy, shared ownership or no copying at all, is the real design question; the rule of three only forces you to answer it. ## How to answer Name the three members, explain that the generated copies are member-wise and therefore shallow for a raw pointer, walk through the double free, and finish with the modern fix: give ownership to a member so the class needs none of the three.

  • Why does a hand-written C++ copy assignment for Image need to handle a = a?
    A naive version frees `pixels_` and then copies from `other.pixels_`, but when `other` is `*this` that buffer was just freed, so it reads freed memory. Allocating and copying into a new buffer before freeing the old one handles self-assignment and also leaves the object intact if the allocation throws. Copy-and-swap gets both properties without an explicit check.
  • Does the C++ compiler still generate a copy constructor for a class with a user-declared destructor?
    Yes. The implicit copy constructor and copy assignment are still defined as defaulted, but the standard deprecates that case and notes that future versions may define them as deleted. Clang reports it with `-Wdeprecated-copy-with-dtor`, which is not part of `-Wall` or `-Wextra`. The move operations, however, are not declared at all.

  • The compiler-generated copy constructor deep-copies memory that a pointer member points to.
  • A double delete just crashes immediately, so tests would always catch it.
  • Writing a destructor is enough for a class that owns heap memory.
  • The rule of three is enforced by the compiler as an error.
  • Copy assignment can simply copy the pointer as long as the destructor checks for nullptr.
open as a page

In C++, how do you make a class non-copyable or move-only with = delete, and why is deleting its move constructor usually a mistake?

level: middleimportance: must knowfreq 62%

basics

~20 s

Declare the copy constructor and copy assignment = delete, and the moves = default if it should still move. Never delete the moves to mean no move: a deleted function still wins overload resolution, so moving an rvalue fails to compile.

open as a page

A C++ Image class gained a user-declared destructor and now std::move(image) copies its pixels; which special members does the compiler still declare, and why?

level: seniorimportance: must knowfreq 58%

basics

~10 s

A user-declared destructor, even = default, stops the compiler declaring the move constructor and move assignment, while the copy operations are still generated, a deprecated case. std::move(image) then binds to const Image& and copies.

open as a page

In C++, how does copy-and-swap implement Image's assignment operator, what guarantee does it give, and what does it cost compared with member-wise assignment?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Copy-and-swap takes the source by value, swaps *this with that parameter through a non-throwing swap, and lets the parameter's destructor free the old state. Assignment fully succeeds or leaves *this unchanged, but always builds a complete copy.

open as a page

Should a C++ codebase make the rule of zero its default policy, and how would you handle the classes that cannot follow it?

level: principalimportance: should knowfreq 40%

basics

~20 s

Yes, 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.

open as a page