Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Can I use this safely in a destructor?

Todays' question is: Can I use this in a destructor, and if yes what are the restrictions I must obey to... For example, I know I'm not supposed to do anything with base classes, since they are gone. But what other restrictions apply? And can I safely assume that the this (as a pointer... ie. memory address... a number) is the same as in the constructor?

like image 760
Ferenc Deak Avatar asked Jan 21 '26 03:01

Ferenc Deak


1 Answers

Can I use this in a destructor

Yes.

For example, I know I'm not supposed to do anything with base classes, since they are gone.

No, the base classes are still intact at this point. Members (and perhaps other base classes) of derived classes have already been destroyed, but members and base classes of this class remain until after the destructor has finished.

But what other restrictions apply?

Virtual functions are dispatched according to the class currently being destroyed, not the former most-derived class. So be careful calling them, and in particular don't call any functions that are pure virtual in this class.

Don't cast this to a derived type, since it is no longer a valid object of that type.

You can't delete this from the destructor, for obvious reasons.

And can I safely assume that the this (as a pointer... ie. memory address... a number) is the same as in the constructor?

Yes, an object's address remains the same from before its constructor runs until after its destructor runs.

like image 73
Mike Seymour Avatar answered Jan 23 '26 16:01

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!