When are static objects destroyed in C ++

Can an object self-destruct?

uekue_ wrote:

when I call this-> ~ myclass () the object is not destroyed! I can still access it and get the correct values!

Yes, the object will be destroyed. And according to the C ++ standard it is "not ok" if it is destroyed again afterwards - if a new object has not been constructed in the same place in between (using "placement new"). And it doesn't matter what is in the destructor or whether it is "trivial" or not.

What you observe here is simply that not everything that is "not ok" according to the C ++ standard immediately leads to an error / crash / ....

The only question is whether you want to rely on your compiler "going anyway", or whether you want to write correct C ++ programs that work with any compiler (that implements the standard correctly).


The best thing is to forget very quickly that you can also write "this-> ~ classname ()".

On the other hand, "delete this" is IMO OK if it is ensured that the object was created with "new". And it is often used like this, e.g. when implementing "intrusive reference counting" (which can also be done without "delete this", but it is often the simplest solution).