Copy Assignment in C++: Assigning One Object to Another
What is Copy Assignment in C++: Assigning One Object to Another? The copy assignment operator (ClassName& operator=(const ClassName& other)) overwrites the state of an already initialized object with the state of another obje...
How does copy assignment (operator=) work in C++, and how does the Copy-and-Swap idiom guarantee strong exception safety?
Explanation & In-Depth Details
- Copy Constructor: Creates a NEW object (`MyClass b = a;` or `MyClass b(a);`).
- Copy Assignment: Reassigns an ALREADY EXISTING object (`b = a;`).
2. The Copy-and-Swap Idiom:
```text
1. Pass right-hand side by value (invoking Copy Constructor to create temporary copy).
2. Swap member data of *this with the temporary copy (using std::swap, noexcept).
3. Temporary copy goes out of scope, automatically releasing old resources in its destructor!
```
Code Example
#include <iostream>
#include <utility>
class Buffer {
private:
size_t size;
int* data;
public:
explicit Buffer(size_t s = 0) : size(s), data(s ? new int[s]() : nullptr) {}
// Copy Constructor
Buffer(const Buffer& other) : size(other.size), data(other.size ? new int[other.size] : nullptr) {
for (size_t i = 0; i < size; ++i) data[i] = other.data[i];
}
// Friend swap function
friend void swap(Buffer& first, Buffer& second) noexcept {
using std::swap;
swap(first.size, second.size);
swap(first.data, second.data);
}
// Copy-and-Swap Assignment Operator (Strong Exception Safety)
Buffer& operator=(Buffer other) { // Passed by value: creates copy
swap(*this, other); // Swap state with temporary copy
return *this; // Old resource deleted when 'other' destructs
}
~Buffer() { delete[] data; }
void print() const {
std::cout << "Buffer size: " << size << "\n";
}
};
int main() {
Buffer b1(100);
Buffer b2(500);
b1 = b2; // Invokes Copy-and-Swap Assignment Operator
b1.print();
return 0;
}Interview Question & Tips
A: In traditional assignment, if an object assigns to itself (`a = a;`), deleting the existing resource first would destroy the very data you intend to copy from.
Q: How does the Copy-and-Swap idiom eliminate self-assignment bugs?
A: Because the argument is passed by value, a distinct copy is created before the swap occurs, making self-assignment completely safe without explicit pointer checks.
Best Practices
• Always return `*this` by reference (`ClassName&`) to support chained assignment expressions (`a = b = c;`).
• Follow the Rule of Five in modern C++ (Destructor, Copy Ctor, Copy Assign, Move Ctor, Move Assign).
This study reference for Copy Assignment in C++: Assigning One Object to Another is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: