This is a dirty hack, but you can destroy and restore yourself:
MyItemT& MyItemT::operator=(const MyItemT& other) { if ( this == &other ) return *this; // "suggested" by Herb Sutter ;v) this->MyItemT::~MyItemT(); try { new( this ) MyItemT( other ); } catch ( ... ) { new( this ) MyItemT(); // nothrow throw; } return *this; }
Edit: so that I do not destroy my authority, I really do not do it myself, I would delete const . However, I discussed changing practices because const simply useful and better used where possible.
Sometimes there is a difference between the resource and the value represented by the object. A member can be const through changes to the value as long as the resource is the same, and it would be nice to get security at compile time.
Edit 2: @Charles Bailey provided this wonderful (and very critical) link: http://gotw.ca/gotw/023.htm .
- Semantics are complex in any derived class
operator= . - It can be inefficient because it does not invoke specific assignment operators.
- This is incompatible with overloaded wiki
operator& (independently) - and etc.
Edit 3: Reflecting on the distinction of “what resource” and “what value”, it seems obvious that operator= should always change the value, not the resource. The resource identifier may be const . In this example, all members are const . If “information” is what is stored inside a “package”, then perhaps the package should be const , but the information is missing.
Thus, the problem is not so much in defining the semantics of assignment, but in the absence of an obvious meaning in this example, if “information” is actually metadata. If any class that owns MyItemT wants to switch it from one package to another, it needs to either refuse, or use auto_ptr<MyItemT> , or refer to a similar hack, as described above (identity verification is not necessary, but catch rest) implemented from the outside. But operator= should not change the resource binding, except as a special feature that absolutely will not interfere with anything else.
Note that this convention works well with Sutter's advice to implement the copy construct in terms of purpose.
MyItemT::MyItemT( MyItemT const &in ) : mMyPacket( in.mMyPacket ) // initialize resource, const member { *this = in; } // assign value, non-const, via sole assignment method