Copy assignment
Copy assignment replaces an existing object's value with a copy of another object of the same type. It is T& operator=(const T&). Unlike the copy constructor, the left-hand side already has a lifetime and must release its old resources first.
Detailed Explanation
b = a; is not construction. b already exists. Assignment must give b the value of a and leave a unchanged. If b owned a buffer, that buffer must be freed or reused. If the copy of a's data throws, b should still be a valid object — ideally unchanged (the strong guarantee).
The implicit copy assignment assigns each member and base. As with the copy constructor, that is correct for types whose members already know how to assign (string, vector) and wrong for a raw owning pointer: the old pointer is overwritten and leaked, and two objects then share the new pointer.
A safe pattern for a raw resource is copy-and-swap:
- Copy the source into a local (
T tmp(other);). If this throws,*thisis untouched. - Swap
*thiswithtmp. Swap isnoexceptif you write it that way. tmpleaves scope and destroys the old resources.
That gives the strong guarantee and also handles self-assignment (a = a;) because the copy is a separate object. A handwritten assign that delete[] data_; data_ = new ... other.data_ blows up on a = a;: it frees the source before reading it.
Always return T& and return *this; so a = b = c; chains. Check if (this == &other) return *this; if you are not using copy-and-swap and your body cannot tolerate self-assignment.
Copy assignment is suppressed if you delete the copy constructor, and the implicit one is not generated if you declare a move constructor or move assignment. Write T& operator=(const T&) = default; or = delete explicitly when you touch any of the five special members, so readers do not have to recall the implicit rules.
Prefer memberwise assignment of RAII members over a custom operator. If the class follows the rule of zero, the generated assignment is the right one and already self-assignment-safe.
Assignment is not the same as construction in overload resolution. T b = a; can be a copy constructor. b = a; after T b; is assignment. T& r = a; is neither; it is a reference bind.
Code Examples
#include <algorithm>
#include <cstddef>
#include <utility>
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& other) {
Buffer tmp(other); // copy first; *this unchanged if this throws
swap(tmp);
return *this;
}
~Buffer() { delete[] data_; }
void swap(Buffer& other) noexcept {
std::swap(data_, other.data_);
std::swap(size_, other.size_);
}
private:
char* data_;
std::size_t size_;
};
int main() {
Buffer a("ada", 3);
Buffer b("al", 2);
b = a; // copy assignment
b = b; // self-assignment is safe
}#include <string>
struct User {
std::string name;
// implicit copy assignment copies name; no operator= needed
};
int main() {
User a{"ada"};
User b{"al"};
b = a; // b.name is "ada"
}Common Gotchas
Self-assignment with delete-then-new
`delete[] data_; data_ = new char[other.size_];` frees `other.data_` when `this == &other`. Use copy-and-swap or a self-assignment guard.
Failed assignment should leave a valid object
if you `delete[]` first and then `new` throws, `data_` is a dangling pointer and the destructor will double-free or crash. Copy-and-swap avoids that order.
Return `T&`, not `void` and not `T`
`void` breaks chaining. `T` by value adds a copy and is not how built-in assignment works.
Implicit assignment after a custom destructor is often wrong
if you needed a destructor, you probably need `operator=` as well, or `= delete`.