Leo Heinsaar Leo Heinsaar - 1 year ago 62
C++ Question

Does modifying class member objects in the destructor result in undefined behavior?

For example:

struct B { int b_; };
struct D : B
{ // D object's lifetime ends here
d_ = 0; // (1) undefined behavior?
b_ = 0; // (2) undefined behavior also?
int d_;

The C++ Standard defines that for an object of type
, its lifetime ends when the destructor
call starts.

Can we interpret this to mean that modifying the object inside the destructor, as in (1), results in undefined behavior?

If so, does the same apply if we modify the base class subobject of
, as in (2)?

Answer Source

Neither access is undefined, they're both perfectly okay.

While you're right that the lifetime ends when the destructor starts, you can still use the object in limited ways, defined as:

N4140 § 3.8 [basic.life] / 6

Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see [class.cdtor].

and [class.cdtor]:

N4140 § 12.7 [class.cdtor] /1

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.

The above clearly states that only after the destructor finishes you can't touch members of that object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download