问题
[class.dtor]/15 reads, emphasis mine:
Once a destructor is invoked for an object, the object no longer exists; the behavior is undefined if the destructor is invoked for an object whose lifetime has ended (3.8).
However, as far as I can tell, this is the only reference in the standard to an object "existing." This also seems to contrast with [basic.life], which is more specific:
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, orthe storage which the object occupies is reused or released.
We have two different wordings here: "the lifetime of an object ends" and "the object no longer exists," the former only happens with a non-trivial destructor and the latter happens with any destructor. What is the significance of the difference? What is the implication of an object no longer existing?
回答1:
The quoted wording would seem to imply that a compiler could correctly insert code that returns the memory associated with an object to the heap at the beginning of its destructor. But doing that would eliminate the ability of an object to reference its own members during destruction, which is required if an object is to be able to destroy itself.
So I think the quoted wording is broken and should be fixed.
Concerning what "lifetime" and "existence" mean, I propose that there are some different contexts, in which they mean different things:
Within the context of construction, lifetime and existence begin when a constructor begins. Outside that context, they begin when a constructor ends.
Within the context of destruction, lifetime and existence end when a destructor ends. Outside that context, they end when destruction begins.
So an object may refer to its own members during construction, and potentially pass itself to functions of other objects, which may refer to the object and its members, and so on. But in general, objects (instances of classes) may not be referenced (without producing undefined behavior) until after one of their constructors has finished.
And an object's destructor may refer to its own members and call functions of other (existing) objects, which may refer to the object being destroyed and/or its members. But in general, an object may not be referenced after its destructor has started.
This sort of multi-contextual definition is what makes the most sense to me, but I can see arguments being made that an object should be considered to be alive from the moment memory is allocated for it to the moment that memory is released, and I would say memory for a shallow copy should be allocated for an object when one of its constructors starts, and released when its destructor ends.
来源:https://stackoverflow.com/questions/30315524/what-does-it-mean-for-an-object-to-exist-in-c