Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 171 ยท Object-Oriented Programming

Copy Constructors and Copy Assignment

Learn C++ copy semantics - when objects are copied, memberwise copies, shallow vs deep copy with a resource-owning class, self-assignment, copy elision and copy-and-swap.

In C++, objects are values. Writing b = a or passing a to a function by value doesn't create a second name for the same object, as it would in Java or Python; it creates a new, independent object with the same contents. For int and std::string that's exactly what you want, and the language does it for your classes too, automatically, by copying each member.

The automatic copy is correct for most classes, and the best classes never need anything else. But a class that directly owns a resource through a raw pointer, such as a heap buffer or a file handle, gets a shallow copy: two objects that both think they own the same resource. That leads to double frees and objects that change behind your back. In this lesson you'll learn exactly when copies happen, what the copy constructor and copy assignment operator do, how to write a correct deep copy, how to survive self-assignment, and the copy-and-swap idiom that makes assignment both short and exception-safe.

Two special member functions

Copying uses two functions with fixed signatures:

C++
class Widget {
public:
    Widget(const Widget& other);              // copy constructor: makes a NEW object
    Widget& operator=(const Widget& other);   // copy assignment: overwrites an EXISTING one
};

The difference is whether the target already exists:

C++
Widget a;
Widget b = a;     // copy constructor (b is being created; the = is not assignment)
Widget c{a};      // copy constructor
b = a;            // copy assignment (b already exists)

The parameter of the copy constructor must be a reference. If it took Widget by value, passing the argument would itself need a copy, which would call the copy constructor, which would need a copyโ€ฆ The compiler rejects that. It's const because copying shouldn't change the source.

When copies happen

Copies appear in more places than b = a. This program logs every special member function so you can watch:

C++ Watching copies happen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Read the output step by step:

  1. Noisy b = a; copy-constructs.
  2. b = a; copy-assigns into the existing b.
  3. Passing by value copy-constructs the parameter, which is destroyed when the function returns. Passing by const& copies nothing. That's why Parameters recommends const T& for large types.
  4. make() returns a temporary, and Noisy c = make(); builds it directly in c: no copy at all. Since C++17 this copy elision is guaranteed for prvalues (temporaries), and it even works for types that can't be copied.
  5. push_back(a) copies a into the vector's own storage. The container owns its elements.

Copy elision also usually happens for a named local returned from a function (NRVO, "named return value optimization"), but that one is allowed, not guaranteed. When it doesn't happen, the object is moved instead, as you'll see in Move Semantics.

The default: memberwise copy

If you don't declare a copy constructor or copy assignment, the compiler generates them. The generated versions copy each base class and member in declaration order, using that member's own copy operation. A std::string member is copied with std::string's copy constructor, a std::vector with the vector's, an int bit by bit.

That's why this class needs no copy code at all:

C++
struct Employee {
    std::string name;
    std::vector<std::string> skills;
    int level = 1;
};

Employee alice{"Alice", {"C++", "SQL"}, 3};
Employee clone = alice;          // copies the string, the vector and the int
clone.skills.push_back("Rust");  // alice.skills is unchanged

Every member manages itself, so the whole object copies correctly. This is the goal you should aim for, called the Rule of Zero.

The problem: shallow copies

Memberwise copy goes wrong when a member is a raw pointer that owns something. Copying a pointer copies the address, not the data it points at. Now two objects point to one buffer.

C++ A shallow copy shares the buffer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Changing copy silently changed original. Now imagine the class has the destructor it obviously needs, ~Scores() { delete[] data_; }. When copy and original go out of scope, both destructors delete the same array. That's a double free: undefined behavior that typically crashes or corrupts the heap. And copy = original; would also leak the array copy owned before. See Dynamic Memory: new and delete for why these bugs are so nasty.

Writing a deep copy

A deep copy gives the new object its own resource with the same contents. Here's the class done properly: a constructor, a destructor, a copy constructor that allocates a new array, and a copy assignment operator.

C++ A deep-copying class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Clang warns about other = other; (-Wself-assign-overloaded); it is written on purpose here to show that the check works.

Two details make the assignment correct:

  • The self-assignment check. Without it, x = x would delete data_ and then copy from the array it just freed. Self-assignment rarely looks this obvious; it usually hides behind references, like scores[i] = scores[j] with i == j.
  • Allocate before you delete. If new throws std::bad_alloc, the object still holds its old, valid array. Deleting first and then failing would leave data_ dangling. This is called the strong exception guarantee: either the assignment succeeds completely or the object is unchanged. See Exception Safety and noexcept.

The copy-and-swap idiom

Hand-written copy assignment repeats the copy constructor's work and is easy to get wrong. Copy-and-swap reuses the copy constructor instead:

  1. Take the parameter by value, so the caller's argument is copied (by the copy constructor) into it.
  2. Swap your members with the parameter's members.
  3. Return. The parameter, which now holds your old resources, is destroyed and frees them.
C++ Copy assignment with copy-and-swap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

What you get:

  • No duplicated logic: copying lives only in the copy constructor.
  • Strong exception guarantee for free: if the copy throws, it throws before *this is touched.
  • Self-assignment safety for free: b = b copies b, swaps with the copy, and the old contents are freed. It's slower than a check, but correct, and self-assignment is rare.
  • Moves too: once the class has a move constructor, the same by-value operator= also handles move assignment.

The cost: copy-and-swap always allocates a new buffer, even when the existing one is big enough to reuse. std::vector therefore doesn't use it. For most classes, correctness and simplicity win.

swap is a noexcept hidden friend, so std::ranges::swap and algorithms like std::sort can find it through argument-dependent lookup. The using std::swap; line lets each member use the best available swap.

Turning copying off

Some objects shouldn't be copied at all: a mutex, a network connection, a unique owner of a GPU texture. Delete the copy operations to make copying a compile error:

C++
class Connection {
public:
    Connection(const Connection&) = delete;
    Connection& operator=(const Connection&) = delete;
    // ...
};

Connection a = open_connection();   // fine: guaranteed elision, no copy needed
Connection b = a;                   // error: use of deleted function

The standard library does this for std::unique_ptr, std::mutex, std::thread and file streams. Such types are usually movable instead, which transfers ownership rather than duplicating it.

Better: let members do it

Writing copy operations by hand is a last resort. The Scores class becomes trivially correct if the raw pointer is replaced by a type that already copies itself:

C++
class Scores {
public:
    explicit Scores(int count) : data_(count) {}
    // No destructor, no copy constructor, no copy assignment needed:
    // std::vector copies deeply, frees its memory and handles self-assignment.
private:
    std::vector<int> data_;
};

Write custom copy operations only for classes whose job is to manage a resource, and keep those classes small. Everything else should be composed from members that already behave correctly. The next two lessons, Move Semantics and The Rule of Zero, Three and Five, complete the picture.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given an existing Widget a, which line calls the copy assignment operator?

    The first, second and fourth lines create a new object, so they call the copy constructor. Assignment to an existing object calls operator=.
  2. 2. A class stores int* data_ that it allocates with new[] and has no copy constructor. What does Holder b = a; do?

    The generated copy constructor copies each member, and copying a pointer copies only the address. If the class deletes the array in its destructor, both objects will delete it.
  3. 3. Why does a hand-written copy assignment allocate the new buffer before deleting the old one?

    If you delete first and new then throws, the object is left pointing at freed memory. Allocating first gives the strong exception guarantee.
  4. 4. In copy-and-swap, why does operator= take its parameter by value?

    The by-value parameter is constructed by the copy constructor (or move constructor for rvalues). Swapping with it installs the new contents, and its destructor frees the old ones.

Summary

  • Objects in C++ are values: copying creates an independent object. The copy constructor makes a new object; copy assignment overwrites an existing one.
  • Copies happen on initialization from another object, pass by value, container insertion and assignment; returning a temporary is never a copy (guaranteed elision in C++17).
  • The compiler-generated copies are memberwise, which is correct when every member manages itself.
  • A raw owning pointer gets a shallow copy: shared data, double frees and leaks. Fix it with a deep copy, a self-assignment-safe assignment, and "allocate before delete".
  • Copy-and-swap writes assignment once, with the strong exception guarantee and self-assignment safety built in.
  • = delete forbids copying. Better still, use members like std::vector and std::unique_ptr so you never write copy code at all.

Next: Move Semantics, where you'll learn how C++ transfers resources instead of copying them.