The copy assignment operator replaces an existing object's resources with a copy of another object's resources. It is declared as operator= and accepts a const& argument:
class Buffer {
public:
Buffer(int n) : size(n), data(new int[n]) {}
Buffer& operator=(const Buffer& other) {
if (this != &other) {
delete[] data;
size = other.size;
data = new int[size];
std::copy#include <algorithm>(other.data, other.data + size, data);
}
return *this;
}
~Buffer() { delete[] data; }
int size;
int* data;
};Warning
Check this != &other, otherwise self-assignment deletes data before copying it.
Note
If new int[size] throws after delete[] data, data becomes a dangling pointer. Use the copy-and-swap idiom.
The copy assignment is invoked when the object already exists, and the right-hand side is an lvalue:
Buffer a(10);
Buffer b(20);
b = a; // Copies a to b.The copy assignment operator can be deleted to prevent usage:
class Buffer {
public:
Buffer& operator=(const Buffer&) = delete;
};
b = a; // ERROR.The copy assignment operator can be defaulted to let the compiler generate it:
class Buffer {
public:
Buffer& operator=(const Buffer&) = default;
};Warning
The compiler-generated copy assignment performs shallow copying, so any deep copying must be done manually.
Dan