Search code examples
c++destructorlanguage-lawyerobject-lifetime

Lifetime of object is over before destructor is called?


I don't understand this:

3.8/1 "The lifetime of an object of type T ends when: — if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or — the storage which the object occupies is reused or released."

If the lifetime ends before the destructor starts, doesn't that mean accessing members in the destructor is undefined behavior?

I saw this quote too:

12.7 "For an object with a non-trivial destructor, referring to any non-static member or base class of the object after the destructor finishes execution results in undefined behavior."

But it doesn't make clear what's allowed during the destructor.


Solution

  • The "lifetime" of an object is relevant for consumers of the object, not the object itself. Therefore a consuming class should not attempt to access members of an object once destruction has started.