C++ · Module 10 · Lesson 41 min read

Copy Constructor & Copy Assignment

When copies happen

  • Copy constructor — a new object from an existing one: Buffer b = a; · Buffer b(a); · passing/returning by value
  • Copy assignment — an existing object gets another's value: b = a;
arduino
Buffer(const Buffer& other);              // copy constructor
Buffer& operator=(const Buffer& other);   // copy assignment

The compiler-generated versions

If you don't write them, the compiler copies each member (memberwise copy). Perfect for members like int, std::string, std::vector — they copy themselves correctly.

The problem: raw owning pointers

perl
class Buffer { int* data_; std::size_t size_; ... ~Buffer() { delete[] data_; } };
Buffer a(10);
Buffer b = a;    // memberwise: b.data_ == a.data_  (SHALLOW copy)

Both destructors delete[] the same memory → double free 💥. Changing b also changes a.

Deep copy

CSS
Buffer(const Buffer& o) : data_(new int[o.size_]), size_(o.size_) {
    std::copy(o.data_, o.data_ + size_, data_);
}

Copy assignment: copy-and-swap idiom ✅

kotlin
Buffer& operator=(Buffer other) {   // by value: the copy constructor does the work
    swap(*this, other);             // take other's data
    return *this;                   // other's destructor frees our old data
}
  • Handles self-assignment (a = a) automatically
  • Exception safe: if copying throws, *this is unchanged

Disabling copies

Some things shouldn't be copied (a file handle, a mutex, a unique resource):

arduino
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;

Best solution: don't own raw pointers ✅

Use std::vector<int> instead of int* + size — then the generated copy operations are correct automatically (the Rule of Zero, next lesson).

Example

C++
#include <algorithm>
#include <iostream>
#include <utility>

class Buffer {
public:
    explicit Buffer(std::size_t n) : data_(new int[n]{}), size_(n) {}
    ~Buffer() { delete[] data_; }

    Buffer(const Buffer& o) : data_(new int[o.size_]), size_(o.size_) {   // deep copy
        std::copy(o.data_, o.data_ + size_, data_);
        std::cout << "  [copy constructor]\n";
    }
    Buffer& operator=(Buffer other) {                                     // copy-and-swap
        std::cout << "  [copy assignment]\n";
        swap(*this, other);
        return *this;
    }
    friend void swap(Buffer& a, Buffer& b) noexcept {
        std::swap(a.data_, b.data_);
        std::swap(a.size_, b.size_);
    }

    int& operator[](std::size_t i) { return data_[i]; }
    std::size_t size() const { return size_; }
    void print(const char* label) const {
        std::cout << label << ":";
        for (std::size_t i = 0; i < size_; ++i) std::cout << ' ' << data_[i];
        std::cout << '\n';
    }
private:
    int* data_;
    std::size_t size_;
};

class Logger {                       // copying makes no sense: delete it
public:
    Logger() = default;
    Logger(const Logger&) = delete;
    Logger& operator=(const Logger&) = delete;
};

void show_by_value(Buffer b) { b.print("  inside function"); }

int main() {
    Buffer a(3);
    a[0] = 10; a[1] = 20; a[2] = 30;

    std::cout << "Buffer b = a;\n";
    Buffer b = a;
    b[0] = 999;                      // independent: a is unchanged
    a.print("a");
    b.print("b");

    std::cout << "Buffer c(5); c = a;\n";
    Buffer c(5);
    c = a;
    c.print("c");

    std::cout << "a = a; (self-assignment)\n";
    a = a;
    a.print("a");

    std::cout << "pass by value:\n";
    show_by_value(a);

    Logger log;
    // Logger copy = log;            // error: copy constructor is deleted
    (void)log;
    return 0;
}

/* Output:
Buffer b = a;
  [copy constructor]
a: 10 20 30
b: 999 20 30
Buffer c(5); c = a;
  [copy constructor]
  [copy assignment]
c: 10 20 30
a = a; (self-assignment)
  [copy constructor]
  [copy assignment]
a: 10 20 30
pass by value:
  [copy constructor]
  inside function: 10 20 30
*/