liveBook · Manning

Big five

As explained in 100 C++ Mistakes and How to Avoid Them

The rule of five is a C++ class-design pattern in which a class considers defining a destructor, copy constructor, copy assignment operator, move constructor, and move assignment operator together.

A class that manages resources should consider its destructor, copy constructor, copy assignment operator, move constructor, and move assignment operator together. These five operations coordinate cleanup, copying, and ownership transfer. section 2.1 section 7.6

The five operations handle distinct responsibilities:

  • Destructor: release resources the object owns. section 7.6
  • Copy constructor and copy assignment: create or update an object while preserving the intended copying semantics. section 7.6
  • Move constructor and move assignment: transfer resources; leave moved-from objects neutralized. section 2.1 section 7.6

Moving a resource-owning Page

A Page that deep-copies its body can avoid copying that body during a move: transfer ownership instead. Use std::move to make an lvalue eligible for move semantics; otherwise, ordinary assignment may copy. section 2.1

Listing 7.9 Adding uniqueness preserving, move construction, and assignment
class TextSection {
    // assume a clever implementation
};
 
class Page {
private:
    TextSection* headers;
    std::unique_ptr<TextSection> body;
public:
    Page(TextSection* h) : headers(h),
body(std::make_unique<TextSection>()) {}
    Page(const Page& o) : headers(o.headers),
body(std::make_unique<TextSection>(*o.body)) {}
    Page& operator=(const Page& o) {
        headers = o.headers;
        body = std::make_unique<TextSection>(*o.body);
        return *this;
    }
    Page(Page&&) = default;                                #1
    Page &operator=(Page&&) = default;                     #2
};
 
int main() {
    Page p1(new TextSection());
    Page p2 = p1;
    return 0;
}

See a Page example with a unique_ptr body, deep-copy operations, and defaulted move construction and assignment. section 7.6

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines the five operations and demonstrates deep copying, cleanup, and defaulted moves with smart pointers.
Examples
Contrasts costly copying with std::move and shows a Page using unique_ptr and defaulted move operations.
What you can do after
Apply the rule by adding move construction and assignment alongside copy operations and a destructor for resource transfer.
How it connects
Connects copy construction and assignment, destructors, move semantics, unique_ptr, and RAII.

Also explained in

Compare how 2 books explain big five →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.