If I have this code:
class A { ... };
class B { ... };
void dummy()
{
A a(...);
B b(...);
...
}
I know that variables a and b will be destroyed in reverse allocation order (b will be destroyed first, then a); but can I be sure that the optimizer will never swap the allocation and construction of a and b? Or I must use volatile to enforce it?
The only guarantees are that any observable side effects (that is, reads and writes to
volatileobjects and calls to I/O functions) of the construction ofawill happen before any observable side effects of the construction ofb, and any side effects ofarequired bybwill happen before they are needed.It’s hard to imagine why you would need a stricter ordering than that, but making the objects
volatilewill ensure thatais completely initialised before initialising any part ofb, although some code from the constructor could still happen beforeais complete.