Systems CourseC/C++ · Linux · Memory
C++ CoreLesson 41 of 442 min read7 questions

Copying & Copy Constructors

Deep-copy a class that owns a resource, or two objects share it and double-free.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. Copy constructor T(const T& other) runs when a new object is built from an existing one: T b = a;, T b(a);, pass-by-value, return-by-value.
  2. The compiler's default copy ctor does a shallow (member-wise) copy — for a pointer member it copies the address, so both objects end up sharing one buffer.
  3. Shared buffer -> both destructors delete it -> double-free (and editing one secretly edits the other). A deep copy (allocate your own buffer + copy the contents) fixes it.
  4. Rule of Three: if you need a custom destructor, you also need a custom copy constructor and copy assignment (C++11 adds move ctor + move assignment = Rule of Five).
  5. Copy constructor builds a new object from an existing one; copy assignment (operator=) is for two objects that already exist (free the old buffer, deep-copy, self-assign guard, return *this).
  6. Pass by const& to avoid triggering a copy; = default (ask for the compiler's version) / = delete (forbid copying, like unique_ptr).

Deep-copy String (the corrected version)

C++
#include <cstring>

class String {
    char*  m_str;
    size_t m_size;              // logical length (strlen), NOT counting the null
public:
    String(const char* s) {
        m_size = strlen(s);
        m_str  = new char[m_size + 1];   // +1 for the null terminator
        strcpy(m_str, s);
    }
    String(const String& o) : m_size(o.m_size) {   // deep copy: own buffer
        m_str = new char[m_size + 1];
        strcpy(m_str, o.m_str);
    }
    ~String() { delete[] m_str; }        // Rule of Three: dtor + copy ctor (+ copy assign)
};
Watch out

Easily confused

shallow vs deep copy
Shallow (default): copies the pointer -> two objects share one buffer -> double-free. Deep (custom): allocate your own buffer + copy the contents.
copy constructor vs copy assignment
Copy ctor: T b = a; builds a NEW object. Copy assignment b = a;: both already exist — free old, deep-copy, self-assign guard, return *this.
Rule of Three vs Rule of Five
Three: destructor + copy ctor + copy assignment (manage a resource). Five adds move ctor + move assignment (C++11, for efficiency).

Test yourself

7 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.