What does it mean for an object to exist in C++?

后端 未结 1 1300
無奈伤痛
無奈伤痛 2021-02-01 15:46

[class.dtor]/15 reads, emphasis mine:

Once a destructor is invoked for an object, the object no longer exists; the behavior is undefined

相关标签:
1条回答
  • 2021-02-01 16:43

    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.

    0 讨论(0)
提交回复
热议问题