FAQ 24.12 Should the assignment operator be implemented by using placement new and the copy constructor?

FAQ 24.12 Should the assignment operator be implemented by using placement new and the copy constructor?

graphics/new_icon.gif

It's a well-known trap!

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.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net