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?