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
Note that they're not malloc and free that are used, but operator new and operator delete. Also, unlike your code, by using new you're guaranteeing exception safety. The nearly equivalent code would be the following.
AnObject* anObject = ::operator new(sizeof(AnObject));
try
{
anObject = new (anObject) AnObject();
}
catch (...)
{
::operator delete(anObject);
throw;
}
anObject->~AnObject();
::operator delete(anObject)
The reset you're proposing is valid, but not idiomatic. It's difficult to get right and as such is generally frowned upon and discouraged.