Creating a Common Function for Copy Constructor and Assignment Operator
A copy constructor and an assignment operator overload often share similar code and differ only in their return type. Can we simplify this by creating a common function that both can use?
Option 1: Explicitly Calling Operator= from Copy Constructor
MyClass(const MyClass& other) { operator=(other); }
This approach is generally discouraged as it introduces problems with old state management and self-assignment. Additionally, it default-initializes all members, even if they are assigned from the other object.
Option 2: Implementing Operator= Using Copy Constructor and Swap
A preferred solution involves implementing operator= using the copy constructor and a swap method:
MyClass& operator=(const MyClass& other) { MyClass tmp(other); swap(tmp); return *this; }
Or even:
MyClass& operator=(MyClass other) { swap(other); return *this; }
The swap function exchanges the ownership of the internal data without cleaning up the existing state or allocating new resources. This approach is self-assignment safe and strongly exception safe, provided that the swap operation is no-throw.
Cautions:
Ensure that the swap method performs a true swap, not the default std::swap, which relies on the copy constructor and assignment operator itself. Use memberwise swap for primitive types and pointer types to guarantee no-throw behavior.
The above is the detailed content of Can a Common Function Simplify Copy Constructor and Assignment Operator Overloads?. For more information, please follow other related articles on the PHP Chinese website!