Usage of "this" in destructor
Asked Answered
T

2

15

Is it valid to call some function in destructor with this argument? Function does not store pointer, but assume full-functional object.

Toscanini answered 11/6, 2012 at 11:33 Comment(1)
The object is fully valid until the very last line of the DTOR. Of course if the DTOR itself tears down pieces of the object (eg. nulls out ptr etc) then you are shooting yourself in the foot, but is entirely your code, not what the cpler generates...Manstopper
R
20

this is still valid in the destructor.

However, you need bear in mind that virtual functions no longer work properly as you might expect once the object is being destroyed; see e.g. Never Call Virtual Functions during Construction or Destruction. Essentially, the dynamic type of the object is modified as each destructor completes.

Repository answered 11/6, 2012 at 11:35 Comment(3)
They do work properly. It's just the definition of properly working functions is different. I mean - they work as designed.Isotone
Or anyway, the committee's definition of "work properly" isn't very useful in practice. I'm sure it's possible to invent some use-case where you do want to call the base class versions of the virtual functions in the base ctor/dtor, and that the committee had something of the kind in mind. Otherwise they'd have given implementations more freedom, and just said that it's UB to make the call. That would probably be more efficient, since the implementation wouldn't have to keep adjusting the vtable pointer (or equivalent) as each dtor completes. As it is, we pay for something we don't use.Forras
@SteveJessop: The re-arranging of the vtable is not needed when the compiler can prove you're not making virtual calls. This is quite often possible, but not so commonly done.Augmentation
V
4

In one word: YES.
It's fully valid to use this in the D`TOR

Volatile answered 11/6, 2012 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.