Warnings and risks of calling constructor and destructor, how are the usual methods?

There is a point in my program where the state of a certain object should be reset "to factory by default". The task boils down to doing everything that is written in the destructor and constructor. I could delete and recreate the object - but can I instead call the destructor and constructor like regular objects? (in particular, I do not want to redistribute the updated pointer to a new instance, since it is delayed in copies elsewhere in the program).

  MyClass {
  public:
        MyClass();
        ~MyClass();

  ...      
  }


  void reinit(MyClass* instance)
  {
        instance->~MyClass();
        instance->MyClass();
  }

Can I do it? If so, are there any risks, reservations, what do I need to remember?

+4
source share
6 answers

, :

void reinit(MyClass* instance)
{
    *instance = MyClass();
}

, .

, , , , , ( , , , ). undefined.

+3

placement-new:

void reinit(MyClass* instance)
{
    instance->~MyClass();
    new(instance) MyClass();
}

.

-:

void MyClass::reinit()
{
    ~MyClass();
    new(this) MyClass();
}

, . http://www.gotw.ca/gotw/023.htm, , :

  • MyClass
  • RAII ( )

.

+2

? , - , , ?

, . , , undefined.


, , :

void reinit(MyClass* instance) {
    *instance = MyClass();
}
+1

, .

auto classObj = std::make_unique<MyClass>();

, . , reset classObj factory , , :

classObj = std::make_unique<MyClass>();

"" MyClass, classObj, MyClass. , , . , reinit. , classObj , .

+1

instance->MyClass(); , .

instance->~MyClass();. :

  • , MyClass
  • , .

, undefined.

instance->~MyClass();, , .

, , . , :

{
    std::string s("hello");
    s.~basic_string();
    new(&s) std::string("goodbye");

    std::cout << s << '\n';
}
+1

new (&instance) MyClass()
0

Source: https://habr.com/ru/post/1607502/


All Articles