TITLE: Yet another assignment operator PROBLEM: sdm@cs.brown.edu (Scott Meyers) // assignment operator for any class X X& X::operator=(const X& rhs) { if (this == &rhs) return *this; // destroy current value of *this this->~X(); // copy rhs into the memory occupied by *this new (this) X(rhs); return *this; } [ This technique is interesting in that it gets around the problem of duplicating assignment statements for members usually contained in both the copy constructor and the assignment operator. -adc ] RESPONSE: rmartin@rcmcon.com (Robert Martin), 11 Jun 93 I don't know about the issue of virtual inheritance that Scott asked about. But I would like to make the following observation about this kind of assignment operator: it allows assignment to alter what reference members refer to! class Part { private: PartNumber& itsPartNumber; }; There are many occasions where reference members are appropriate. I like to use them when the association between the contained and the containing class lasts the lifetime of the containing class; but when the contained object has a longer lifetime. In the example above, PartNumbers can exist long before the Part that they become associated with. Using reference in this context is nicer than using pointers since the reference cannot be changed, and cannot point to nothing. However, using references in a class with a normal assignment operator caused problems, because the normal assignment operator could not redirect the reference. Scott's method utterly destroys the old lvalue and reconstructs it, allowing the references to be reinitialized. I like it. I wonder if this form of assignment operator should not become the Default for any class with a copy constructor, instead of memberwise copy. And if the standard should not guarantee that Scott's virtual base question is not an issue. RESPONSE: maxtal@physics.su.OZ.AU (John Max Skaller), 12 Jun 93 What a wonderfully acute observation! This form of assignment allows rebinding of references. Default assignment ignores references. User written assignment operators may chose to implement 'deep assignment' on references, (as well as allowing rebinding by the same technique as above). That is three distinct treatments of references in assignment. [ ... ]