0

In the standard document(14882:2020), it says:

The lifetime of an object o of type T ends when:

if T is a non-class type, the object is destroyed, or

if T is a class type, the destructor call starts, or

the storage which the object occupies is released, or is reused by an object that is not nested within o (6.7.2).

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling a destructor or pseudo-destructor (7.5.4.4) for the object.

But in the following codes:

class X{
public:
    int x = 1;
    ~X(){cout<<"End Lifetime.\n";}
};
int main()
{
    X a{};
    a.~X();
    a.x = 2;
    cout<<a.x<<endl;
    return 0;
}

with the outputs of:

End Lifetime.
2
End Lifetime.

According to the standard, a.~X(); has ended the lifetime of a. But we can still access it through the handle a. Furthermore, at the end of the program, a has been destruct again. Isn't that strange?

Why we don't (or can't) avoid this by treating the object as completely "dead" and "disappearing"?

Does it mean the 'Lifetime of Object' is just an abstract concept that does nothing to the actual behavior of the program?

zclll
  • 77
  • 7
  • 4
    Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash. See [using an object after it's destructor is called](https://stackoverflow.com/questions/13067765/using-an-object-after-its-destructor-is-called) – Jason Sep 18 '22 at 15:44
  • Basically the only time you should explicitly call a destructor is after a placement new. Just don't do it otherwise. – Some programmer dude Sep 18 '22 at 15:45
  • *"treating the object as completely "dead" and "disappearing""* - how exactly would that work in your opinion? Do you want the compiler to statically analyze the lifetime of all objects in your program? Or do you want some runtime overhead (which goes against the core ideas of C++) for having automatic lifetime checks? – UnholySheep Sep 18 '22 at 15:48
  • @Someprogrammerdude If that's true, my doubts can be answered. Where can I find further information about that? Thx~ – zclll Sep 18 '22 at 17:10
  • @UnholySheep I'm just confused because I thought when I explicitly called dtor of an object that made its lifetime end, at least it would enter a special state in which other behaviors may be undefined, but dtor wouldn't be called again. I know the zero-overhead principle. But in this situation, I can't understand the necessity of the concept 'Lifetime'. – zclll Sep 18 '22 at 17:23
  • Once the destructor has been called, the object can't be used in any way ever again. Any attempt of doing that will lead to undefined behavior. And in C++ it's not really the compilers role to prevent you from that, it's your job as the programmer to make sure that doesn't happen. – Some programmer dude Sep 19 '22 at 16:16

0 Answers0