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
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.