On the last line of a destructor, I have a diagnostic type message which takes a printf
-like form:
"object destroyed at %p", this
I have concerns though about how well this
is defined at such a point.
Should I have such reservations? Is the behaviour well-defined?
In one word: YES.
Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the {body} and even in the initialization list) if you are careful.
Rules for C++ Destructors According to C++ destructor the statement should begin with a tilde () and the same class name. Destructors are not equipped with parameters or a return form. Destructors are invoked automatically and cannot be invoked manually from a program. Destructors cannot be overloaded.
According to the C++ Standard (12.4 Destructors)
8 After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X’s direct non-variant non-static data members, the destructors for X’s direct base classes and, if X is the type of the most derived class (12.6.2), its destructor calls the destructors for X’s virtual base classes.
So your code is well-formed. All destructors of non-static data members and base classes are called after executing the body of the destructor.
Well, the pointer itself certainly still exists (it's just an address, after all). There should be no problem to print the pointer value.
On the other hand, everything that you did in the destructor has already happened. Attributes may already have been delete
'd, etc, so you have to avoid anything that accesses those.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With