Sometimes it's nice to start over. In C++ I can employ this following simple manoeuvre:
{ T x(31, Blue, false); x.~T(); // enough with the old x ::new (&x) T(22, Brown, true); // in with the new! // ... }
At the end of the scope, the destructor will run once again and all seems well. (Let's also say T
is a bit special and doesn't like being assigned, let alone swapped.) But something tells me that it's not always without risk to destroy everything and try again. Is there a possible catch with this approach?
Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed. Destructor is also a special member function like constructor.
A destructor is used to destroy the objects created that have been created by a constructor. It has a same name as its class, just that it is preceded by a tidle.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ).
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
I think the only way to make this really safe to use is to require the called constructor to be noexcept
, for example by adding a static_assert
:
static_assert(noexcept(T(22, Brown, true)), "The constructor must be noexcept for inplace reconstruction"); T x(31, Blue, false); x.~T(); ::new (&x) T(22, Brown, true);
Of course this will only work for C++11.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With