Copy constructor
The copy constructor creates a new object as a copy of an existing one of the same type. Its signature is T(const T&) (or T(T&)). It runs for T b = a;, pass-by-value, and return-by-value when a move or elision does not apply.
Detailed Explanation
C++ objects are values. User b = a; is not "two names for one heap object". It is a second User that should behave like the first. The copy constructor is the function that fills that second object.
The compiler writes one for you if you do not. The implicit copy constructor copy-constructs each base and each member. For a class of std::string and int, that is correct: the string duplicates its buffer, the int is copied. For a class that holds a raw int* owner_, the implicit copy copies the pointer. Two objects now free the same allocation. That is why a user-written destructor almost always needs a user-written copy constructor (or a deleted one).
Signature details. T(const T&) can bind to const and non-const sources and to temporaries (which then prefer a move if one exists). T(T&) refuses const sources and is the old auto_ptr-style signature; do not use it. T(T) is not a copy constructor; it is ill-formed as a constructor taking the type by value.
When it is called, in principle:
T b(a);andT b = a;(the latter is copy-initialisation and can also call a converting constructor plus a copy, usually elided).- Passing a
Tby value. - Returning a
Tby value, when copy elision does not apply and a move constructor is not chosen. T b = {a};in some forms.
In practice, copies of temporaries are often constructed in place (copy elision) or moved. You still write the copy constructor as if it will run, because it will run for named sources.
A correct copy constructor copies the value, not the identity. Two std::vectors after a copy have equal elements and different buffers. A class that is not meant to be copied (std::unique_ptr, a std::thread, a file handle) should T(const T&) = delete. Deleting the copy constructor also deletes the implicit copy assignment unless you write one, and it suppresses the implicit move members unless you default them.
Member initialiser lists are the right place to copy members: Buffer(const Buffer& other) : data_(other.data_), size_(other.size_) {}. If you need a deep copy of a raw pointer, allocate first, copy the bytes, then set the pointer. If the allocation throws, members already initialised are destroyed and you leak nothing.
Prefer the rule of zero: store owning pointers in unique_ptr or containers, and let the compiler generate the copy (or fail to, for unique_ptr, which is what you want for exclusive ownership). Write a copy constructor when the class has an invariant that default memberwise copy would break (a cached pointer into your own buffer, a refcount you must increment).
Code Examples
#include <algorithm>
#include <cstddef>
#include <iostream>
class Buffer {
public:
Buffer(const char* s, std::size_t n)
: data_(new char[n]), size_(n) {
std::copy(s, s + n, data_);
}
Buffer(const Buffer& other)
: data_(new char[other.size_]), size_(other.size_) {
std::copy(other.data_, other.data_ + size_, data_);
}
Buffer& operator=(const Buffer&) = delete; // see copy-assignment page
~Buffer() { delete[] data_; }
std::size_t size() const { return size_; }
private:
char* data_;
std::size_t size_;
};
int main() {
Buffer a("ada", 3);
Buffer b = a; // copy constructor
std::cout << b.size() << '\n'; // prints: 3
}#include <memory>
#include <string>
struct Session {
std::string id;
// unique_ptr is not copyable, so Session is not copyable either.
std::unique_ptr<int> nonce;
};
int main() {
Session a{"s1", std::make_unique<int>(1)};
// Session b = a; // error: copy constructor is deleted
(void)a;
}Common Gotchas
Implicit copy of a raw owning pointer
two destructors `delete` the same address. If you write `~T`, decide whether to copy (deep copy) or delete the copy constructor.
Copy-initialisation can call a converting constructor
`T b = 3;` is not necessarily the copy constructor. It is `T(3)` plus an optional elided copy.
`= default` is not the same as omitting it once you have declared another special member
if you wrote a move constructor, the implicit copy constructor is suppressed. Write `T(const T&) = default;` if you still want copies.
Copying a type with a pointer into itself
after a naive memberwise copy, the pointer still addresses the *source*'s buffer. Recompute interior pointers after the deep copy.