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?
, :
void reinit(MyClass* instance) { *instance = MyClass(); }
, .
, , , , , ( , , , ). undefined.
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
? , - , , ?
, . , , undefined.
, , :
auto classObj = std::make_unique<MyClass>();
, . , reset classObj factory , , :
classObj
classObj = std::make_unique<MyClass>();
"" MyClass, classObj, MyClass. , , . , reinit. , classObj , .
reinit
instance->MyClass(); , .
instance->MyClass();
instance->~MyClass();. :
instance->~MyClass();
, undefined.
instance->~MyClass();, , .
, , . , :
{ std::string s("hello"); s.~basic_string(); new(&s) std::string("goodbye"); std::cout << s << '\n'; }
new (&instance) MyClass()
Source: https://habr.com/ru/post/1607502/More articles:Modify JSONAPI converter? - javaSolr: sorry, no dataimport handler defined - luceneSearching column index based on content in cell array - vectoriOS9: optimizing iPhone 5 for loss - iosCSS file: SyntaxError: expected expression, received '.' - javascriptStandalone Django ORM - default settings are not recognized - pythonSpring Download. How to disable initialization JPA Conditionaliy - springОшибка установки Checkstyle Intellij Idea - javaСоздать динамические определения подгонки кривой для рядов Фурье динамически - pythonElement created using XSLT templates not visible to Selenium - xsltAll Articles