The copy assignment operator is an operator used in assignment and one of The Big Four. It differs from a constructor, because the copy assignment operator might have to clean up the previous (to-be-overwritten) instance its resources.
There are multiple idioms for overloading a copy assignment operator:
- the 'classic way', which checks for self-assignment
- the 'swap idiom'
struct MyClass { //Default constructor MyClass(const int x = 0) : m_x(x) {} //Canonical form of copy assignment operator MyClass& operator=(const MyClass& other) { //Prevent self-assignment if (this != &other) { //Copy member variables m_x = other.m_x; } //Return *this by convention return *this; } ///Read the member variable int GetX() const { return m_x; } private: //Member variables int m_x; };
#include <algorithm> struct MyClass { //Default constructor MyClass(const int x = 0) : m_x(x) {} //Canonical form of copy assignment operator MyClass& operator=(const MyClass& other) { MyClass temp(other); Swap(temp); //Return *this by convention return *this; } ///Read the member variable int GetX() const { return m_x; } private: //Member variables int m_x; void Swap(MyClass& other) { std::swap(m_x,other.m_x); } };
Operating system(s) or programming environment(s)
Lubuntu 12.10 (quantal)
Qt Creator 2.5.2
- G++ 4.7.2
Libraries used:
STL: GNU ISO C++ Library, version
4.7.2
Qt project file: CppCopyAssignmentOperator.pro
struct MyClassClassic { //Default constructor MyClassClassic(const int x = 0) : m_x(x) {} //Canonical form of copy assignment operator MyClassClassic& operator=(const MyClassClassic& other) { //Prevent self-assignment if (this != &other) { //Copy member variables m_x = other.m_x; } //Return *this by convention return *this; } ///Read the member variable int GetX() const { return m_x; } private: //Member variables int m_x; }; #include <algorithm> struct MyClassSwap { //Default constructor MyClassSwap(const int x = 0) : m_x(x) {} //Canonical form of copy assignment operator MyClassSwap& operator=(const MyClassSwap& other) { MyClassSwap temp(other); Swap(temp); //Return *this by convention return *this; } ///Read the member variable int GetX() const { return m_x; } private: //Member variables int m_x; void Swap(MyClassSwap& other) { std::swap(m_x,other.m_x); } }; #include <cassert> int main() { { MyClassClassic x(1); MyClassClassic y(2); assert(x.GetX() != y.GetX()); x = y; assert(x.GetX() == y.GetX()); } { MyClassSwap x(1); MyClassSwap y(2); assert(x.GetX() != y.GetX()); x = y; assert(x.GetX() == y.GetX()); } }


