Skip to content

Copy Semantics and the Rule of Five

Beginning of the lesson

Copy Semantics and the Rule of Five

Deciding what it means to copy, assign and destroy your own resource-owning types

Big Idea: Every C++ class already knows how to be copied, assigned and destroyed - the compiler writes those operations for you. That default is perfect for classes made of value members, but dangerous for a class that owns a raw resource (heap memory, a file handle, a socket). The default copy duplicates the pointer instead of the thing it points to, so two objects end up owning the same resource and free it twice. The Rule of Five tells you when and how to take control of these operations.
By the end you will be able to:
  • name the special member functions the compiler generates and say what each does by default,
  • explain the difference between a shallow and a deep copy and why shallow copy of an owning class causes a double free,
  • write a correct copy constructor and copy-assignment operator (including the copy-and-swap idiom),
  • apply the Rule of Three, the Rule of Five and the Rule of Zero, and use =default and =delete to control which operations exist.

This topic assumes you already know raw pointers, new/delete and RAII. It is the missing piece that Introduction to Move Semantics quietly depends on: move operations only make sense once you understand copy operations.

1. The special member functions

There is a small set of member functions that the compiler will generate for you if you do not write them. They are called the special member functions. For copy semantics, three of them matter first:

  • Destructor ~T() - runs when the object dies; its job is to release whatever the object owns.
  • Copy constructor T(const T&) - builds a brand-new object as a copy of an existing one (T b = a; or T b(a);).
  • Copy-assignment operator T& operator=(const T&) - replaces the contents of an already-built object with a copy of another (b = a;).

Two more join them in modern C++ (the move operations, which you met in the previous topic): the move constructor T(T&&) and the move-assignment operator T& operator=(T&&). Together these five are the subject of the Rule of Five.

The compiler-generated copy operations do a memberwise copy: they copy each member the way that member copies itself. For an int that copies the value; for a raw pointer that copies the address - not the memory it points at. That single fact is the root of every bug in this topic.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers