Re-creating the constructor of a statically assigned object

I have an object that has been statically allocated. This object does not have operator=

and I need to restore it.

So, it does n't work for me :

myObj = T(...);

      

My current approach:

myObj.~T()
new(&myObj) T(...);

      

But it doesn't feel right, so I was wondering if there is some kind of pitfall I'm missing here.

+3


source to share


2 answers


If the object was statically allocated and you want to reallocate it without resorting to UB, your best bet is to take control of the scope and decide

  • When last you can wait until you select an object
  • When you are early you must free the object


To understand better, consider an example

void foo()
{
    {
    Foo obj(...); // obj gets allocated
    // Code which uses obj
    } // obj gets automatically de-allocated
    {
    Foo obj; // obj gets allocated (default constructed)
    // Code which uses obj
    } // obj gets automatically de-allocated
}

      

+1


source


Create the object like std::experimental::optional

and now you can recreate it at will. Just remember to make sure it exists before using it every time.



boost

also has such a class, and in my experience you can use your own extra file as well.

+1


source







All Articles