- Copy Constructor: Creates a NEW object (
MyClass b = a;orMyClass b(a);). - Copy Assignment: Reassigns an ALREADY EXISTING object (
b = a;).
main.cpp
#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;
}