Suppose I'm implementing some class A that has a clear() method that should set the object state to the "brand new" state as if it has just been created with a constructor:
- I should free all the resources that the current object is using (exactly the same thing
A::~A()does), - and then I should initialize those resources again (exactly the same thing
A::A()does).
So my initial idea was as follows:
void A::clear() {
this->~A();
*this = A();
}
However, I was told that this code causes UB since I cannot dereference this after calling its destructor. But at the same time I was told a better idea as well: if we use placement new, there is no dereferencing, so this actually might work:
void A::clear() {
this->~A();
new (this) A();
}
This feels extremely uncomfortable and as error-prone as it gets... So is this code actually valid?