Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validity of "this" in destructor

Tags:

c++

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?

like image 269
P45 Imminent Avatar asked Sep 03 '14 07:09

P45 Imminent


People also ask

Can we use this pointer in destructor?

In one word: YES.

Is it safe to use this in constructor?

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.

What are the rules of destructor?

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.


2 Answers

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.

like image 140
Vlad from Moscow Avatar answered Sep 23 '22 13:09

Vlad from Moscow


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.

like image 43
Sjlver Avatar answered Sep 20 '22 13:09

Sjlver