C Programming FAQs: Frequently Asked Questions
FAQ 24.12 Should the assignment operator be implemented by using placement new and the copy constructor?
It is tempting to avoid duplicate code for the assignment operator for class X by trying something like this. #include <new> using namespace std; X& X::operator= (const X& rhs) { if (this != &rhs) { this->~X(); new(this) X(rhs); } return *this; } There are many problems with this approach. rhs will be sliced whenever it is not of type X, and the dtor-new-ctor sequence does not bode well for performance. Worst of all, consider what this does to future classes derived from X, even if operator=() isn't declared virtual in a base class of X (which introduces issues of its own). It's good to minimize duplicate code, but the smart way to do it is to put common code into a private: member function that can be used by both the copy ctor and assignment operator. That's a safe way to reuse code; the approach in the example should be avoided. |