Call destructor and then constructor (resetting an object)

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

    You cannot call the constructor in the manner indicated by you. Instead, you can do so using placement-new (like your code also indicates):

    new (anObject) AnObject();
    

    This code is guaranteed to be well-defined if the memory location is still available – as it should be in your case.

    (I've deleted the part about whether this is debatable code or not – it's well-defined. Full stop.)

    By the way, Brock is right: how the implementation of delete isn't fixed – it is not the same as calling the destructor, followed by free. Always pair calls of new and delete, never mix one with the other: that's undefined.

提交回复
热议问题