Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In this answer, Ryan directly calls the virtual destructor. I've tested the code in VS2010, and it correctly calls all destructors (tested with logging statements). Is it actually valid to do so? What are the problems, flaws or even the good points of such an approach?

I can only think of it as a way to really force a reset of the actual type, even if they don't override a virtual reset function, since they atleast have to clean up in their destructors.

Also, eactly what kind of side-effects does a call to the destructor bring? Is it undefined behaviour to use the object after such a destructor call? What if one immediatly reinitializes it with a new (this) MyClass(); call?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

Calling a destructor manually is a perfectly valid thing, regardless of if it's virtual. You just want to make sure that it's just called once for every constructor call.

Is it undefined behaviour to use the object after such a destructor call? 

Yes.

What if one immediatly reinitializes it with a new (this) MyClass(); call?

Still horrifically undefined.

Do not manually destruct an object unless you had to manually place it, e.g. with placement new or some equivalent, and definitely do not ever re-initialize a destructed object like that and hope to avoid UB. Classes like std::vector very explicitly make accessing destroyed objects UB, and it remains UB even if you then make a new element in it's place.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...