Call destructor and then constructor (resetting an object)

后端 未结 10 1428
悲&欢浪女
悲&欢浪女 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:29

    Why not implement a Clear() method, that does whatever the code in the body of the destructor does? The destructor then just calls Clear() and you call Clear() directly on an object to "reset it".

    Another option, assuming your class supports assignment correctly:

    MyClass a;
    ...
    a = MyClass();
    

    I use this pattern for resetting std::stack instances, as the stack adaptor does not provide a clear function.

提交回复
热议问题