Skip to main content

Lesson 3 of 5

Copy Semantics - Copy Constructor & Copy Assignment

The **copy constructor** creates a new object as a copy of another. The **copy assignment operator** replaces an existing object's state with a copy of another. For classes managing resources (dynamic memory, file handles), the compiler-generated shallow copies are almost always wrong - you need deep copies. The **copy-and-swap idiom** provides a strong exception-safe implementation of copy assignment.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Copy Constructor, Copy Assignment & Copy-and-Swap

Copy Constructor, Copy Assignment & Copy-and-Swap
#include <iostream>
#include <algorithm>   // std::swap, std::copy
#include <cstring>     // strlen
#include <stdexcept>

class MyString {
    char*  data_;
    size_t size_;

public:
    // ── Constructor ───────────────────────────────────────────
    explicit MyString(const char* str = "")
        : size_(std::strlen(str))
        , data_(new char[size_ + 1])
    {
        std::memcpy(data_, str, size_ + 1);
        std::cout << "MyString: constructed "" << data_ << ""
";
    }

    // ── Destructor ────────────────────────────────────────────
    ~MyString() {
        std::cout << "MyString: destroyed "" << data_ << ""
";
        delete[] data_;
    }

    // ── Copy constructor - deep copy ──────────────────────────
    MyString(const MyString& other)
        : size_(other.size_)
        , data_(new char[size_ + 1])   // new allocation
    {
        std::memcpy(data_, other.data_, size_ + 1);
        std::cout << "MyString: copy constructed
";
    }

    // ── Copy assignment - copy-and-swap idiom ─────────────────
    // 1. Take by value - invokes copy constructor (strong exception safe)
    // 2. Swap with *this
    // 3. Old data destroyed in rhs's destructor
    MyString& operator=(MyString rhs) {  // rhs is a copy
        std::swap(data_, rhs.data_);     // swap internals
        std::swap(size_, rhs.size_);
        return *this;
        // rhs (now holding old data) is destroyed here - safe cleanup
    }

    // ── Interface ─────────────────────────────────────────────
    const char* c_str() const { return data_; }
    size_t      size()  const { return size_; }

    friend std::ostream& operator<<(std::ostream& os, const MyString& s) {
        return os << s.data_;
    }
};

int main() {
    std::cout << "--- Constructing ---
";
    MyString s1("Hello");
    MyString s2("World");

    std::cout << "
--- Copy construct ---
";
    MyString s3(s1);   // copy constructor
    std::cout << "s3 = " << s3 << "
";

    std::cout << "
--- Copy assign ---
";
    s2 = s1;   // copy assignment (copy-and-swap)
    std::cout << "s2 = " << s2 << "
";

    std::cout << "
--- Self-assign (safe with copy-and-swap) ---
";
    s1 = s1;   // copy-and-swap handles self-assignment correctly
    std::cout << "s1 = " << s1 << "
";

    std::cout << "
--- Compiler-generated shallow copy (BAD example) ---
";
    // Without user-defined copy: s3 = s1 would copy the pointer
    // Both s1 and s3 would point to the same char array
    // When s3 is destroyed: double-free! (fixed by our deep copy above)

    std::cout << "
--- Destruction ---
";
    return 0;
}

Common Mistakes

  • Shallow copy of pointers - without a user-defined copy constructor, `MyString s2 = s1` copies the `char*` pointer, not the pointed-to data. Both objects' destructors will `delete[]` the same memory - double-free and crash.
  • Classic copy assignment self-assignment bug - `delete[] data_; data_ = new char[...]; memcpy(data_, other.data_, ...)` - if `this == &other`, we delete `other.data_` (same as `data_`) THEN try to copy from the now-deleted memory. Copy-and-swap avoids this entirely.
  • Forgetting to return `*this` from copy assignment - assignment operators must return `T&` to support chaining: `a = b = c`. Returning void breaks chaining.

Tip

Tip

Practice Copy Semantics Copy Constructor Copy Assignment in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Why Default Memberwise Copy Causes Double Free, and Implementing Deep Copy Constructors

Practice Task

Note

Practice Task - (1) Write a working example of Copy Semantics Copy Constructor Copy Assignment from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Copy Semantics Copy Constructor Copy Assignment is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • The **copy constructor** creates a new object as a copy of another.
  • Shallow copy of pointers - without a user-defined copy constructor, `MyString s2 = s1` copies the `char*` pointer, not the pointed-to data. Both objects' destructors will `delete[]` the same memory - double-free and crash.
  • Classic copy assignment self-assignment bug - `delete[] data_; data_ = new char[...]; memcpy(data_, other.data_, ...)` - if `this == &other`, we delete `other.data_` (same as `data_`) THEN try to copy from the now-deleted memory. Copy-and-swap avoids this entirely.
  • Forgetting to return `*this` from copy assignment - assignment operators must return `T&` to support chaining: `a = b = c`. Returning void breaks chaining.

Topics in This Module

0/5 done