Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destroy and then construct new object using the same variable

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?

like image 627
Kerrek SB Avatar asked Jan 12 '12 02:01

Kerrek SB


People also ask

Which method is automatically called if it exists when an object is destroyed?

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.

What destroys the objects created by the 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.

When an object is destroyed which function is called?

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 ( ~ ).

Does destructor destroy the object?

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.


1 Answers

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.

like image 182
Grizzly Avatar answered Oct 04 '22 05:10

Grizzly