jkoshy
jkoshy

Reputation: 1863

Invocation sequence of constructors and destructors?

Suppose we have two objects with automatic storage duration:

{
   ClassA objA(...);
   ClassB objB(...);

   // [A] code that uses objA and objB.

   // [B] objA is no longer used after this point.

   // ... more code ...

}  // [C] objA and objB go out of scope.
  1. Does the C++ standard specify the relative sequencing of the constructors for objA and objB? For example, can we assume that any side-effects caused by objA's constructor will be visible when objB's constructor is invoked?
  2. At [C] destructors for objA and objB will be invoked. Is there a similar sequencing requirement on these destructors?
  3. Finally, if liveness analysis shows that objA is dead after point [B], is a C++ compiler allowed to invoke the destructor for objA "early", i.e., between points [B] and [C] in the code?

Upvotes: 0

Views: 166

Answers (2)

juanchopanza
juanchopanza

Reputation: 227370

1 Does the C++ standard specify the relative sequencing of the constructors for objA and objB? For example, can we assume that any side-effects caused by objA's constructor will be visible when objB's constructor is invoked?

Yes. objA is constructed before objB.

2 At [C] destructors for objA and objB will be invoked. Is there a similar sequencing requirement on these destructors?

Yes, objB is destroyed before objA. The order of destruction is the reverse of the order of construction.

3 Finally, if liveness analysis shows that objA is dead after point [B], is a C++ compiler allowed to invoke the destructor for objA "early", i.e., between points [B] and [C] in the code?

Not if there are side effects. The compiler must follow the as-if rule.

To clarify: the as-if rule applies to all of the the three points above.

Upvotes: 2

billz
billz

Reputation: 45410

§6.6.2

On exit from a scope (however accomplished), objects with automatic storage duration (3.7.3) that have been constructed in that scope are destroyed in the reverse order of their construction.

Pretty much answers all of your three questions from this reference.

Upvotes: 1

Related Questions