C++ · Intermediate level

Intermediate level · Module 1: Classes, Constructors and Object Lifetime · Lesson 3 of 3

Copying Objects: Rule of Zero and Rule of Three

Understand what happens when objects are copied and why most classes should not define copy operations or destructors at all.

In this lesson you will

  • Explain copy construction and copy assignment
  • Apply the rule of zero, and recognise when the rule of three applies

Key concepts

copy constructorcopy assignmentshallow vs deep copyrule of zero / three

The lesson

Copying an object calls its copy constructor; assigning one existing object to another calls copy assignment. For classes built from std::string, std::vector and other well-behaved members, the compiler-generated versions copy each member correctly.

Problems arise when a class manages a raw resource such as memory from new. The generated copy only copies the pointer (a shallow copy), so two objects delete the same memory — a crash or corruption. If you write a destructor, you almost always need a copy constructor and copy assignment too: the rule of three.

The better path is the rule of zero: do not manage raw resources in ordinary classes. Use standard containers and smart pointers as members, write no destructor or copy operations, and let the compiler generate correct ones.

Step by step

  1. Copy a class built from std::string members and confirm the copies are independent.
  2. Study a class holding a raw new[] pointer and observe a double delete under a sanitizer.
  3. Fix it by replacing the raw pointer with std::vector.
  4. Delete the now-unneeded destructor.

Practice activity

Refactor a provided Buffer class from raw memory to std::vector, removing its destructor and custom copy code.

Expected result: The refactored class copies correctly, has no hand-written destructor and runs cleanly under AddressSanitizer.

Check your understanding

  1. What is the rule of zero?

    Show answer

    Classes should not manage raw resources, so they need no custom destructor or copy operations.

  2. Why is a shallow copy of a raw owning pointer dangerous?

    Show answer

    Two objects end up deleting the same memory.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.