This is a bad pattern. Copy-and-swap is better.
foo & operator = ( foo const & other ) {
static_assert ( noexcept( new (this) foo() ), "Exception safety violation" );
this-> ~ foo();
try {
new (this) foo( other );
} catch (...) {
new (this) foo(); // does not throw
throw;
}
return * this;
}
As long as foo
is not polymorphic, what could go wrong? (However, assume that it is a base class.)
Background: I'm dealing with local-storage type erasure, and the alternative is to implement swap
as two hard-coded assignments through a local storage space. The objects in the memory blobs of the source and destination are of different types and simply can't swap with each other. Copy/move construction defined in terms of such a swap is twice as complicated for seemingly no gain.