Is it a Bad Idea to destructor and reconstruct an object in the assignment operator?

Viewed 172

I haven't programmed much since before the C++11 standard, so I'm still learning some of the newer idioms and how to use them.

I've been thinking how to write efficient assignment operators, and I just found out how placement new works.

So now I'm considering writing assignment operators by (1) destroying the object, and (2) using placement new to call the copy constructor, like:

MyClass& MyClass::operator=(const MyClass& other)
{
    if (&other == this)
        return (*this);

    this -> ~MyClass();
    return *(new (this) MyClass(other));
}

Normally I would never use an object after destructing it. BUT, I am immediately reconstructing it. Is this idiom safe and elegant to use? Or is it a TERRIBLE idea and I should immediately

delete this;
1 Answers

This approach is not new, and people have tried it before. The main problem, as stated in the comments (the rest is less serious) is a potential for exception thrown during the call to the copy constructor.

If that happens, you end up in a very bad situation - you did call destructor already, so that object is no longer valid, and there is no undoing that. Even if you catch the exception, there is still no good recourse, as there is nothing you can do to restore the object.

There are also classes which need a certain pre-condition before destructor can be called (std::thread is a prime example). While I personally do not like this, those classes exist.

If you are doing this for your own fully-controlled class, where you know for a fact copy-constructor doesn't throw (and ideally annotated as such), and random destructing of the class is acceptable, this approach is viable - although, usually not worth it.

Related