Call destructor and then constructor (resetting an object)

后端 未结 10 1427
悲&欢浪女
悲&欢浪女 2020-12-05 18:09

I want to reset an object. Can I do it in the following way?

anObject->~AnObject();
anObject = new(anObject) AnObject();
// edit: this is not allowed: anO         


        
10条回答
  •  粉色の甜心
    2020-12-05 18:26

    Technically it is bad practice to call constructors or destructors explicitly.

    The delete keyword ends up calling them when you use it. Same goes for new with constructors.

    I'm sorry but that code makes me want to tear my hair out. You should be doing it like this:

    Allocate a new instance of an object

    AnObject* anObject = new AnObject();
    

    Delete an instance of an object

    delete anObject;
    

    NEVER do this:

    anObject->~AnObject(); // My step 1.
    free(anObject)
    

    If you must "reset" an object, either create a method which clears all the instance variables inside, or what I would recommend you do is Delete the object and allocate yourself a new one.

    "It is the core of the language?"

    That means nothing. Perl has about six ways to write a for loop. Just because you CAN do things in a language because they are supported does mean you should use them. Heck I could write all my code using for switch statements because the "Core" of the language supports them. Doesn't make it a good idea.

    Why are you using malloc when you clearly don't have to. Malloc is a C method.

    New and Delete are your friends in C++

    "Resetting" an Object

    myObject.Reset();
    

    There you go. This way saves you from needlessly allocating and deallocating memory in a dangerous fashion. Write your Reset() method to clear the value of all objects inside your class.

提交回复
热议问题