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 volatile
objects and calls to I/O functions) of the construction of a
will happen before any observable side effects of the construction of b
, and any side effects of a
required by b
will happen before they are needed.
It's hard to imagine why you would need a stricter ordering than that, but making the objects volatile
will ensure that a
is completely initialised before initialising any part of b
, although some code from the constructor could still happen before a
is complete.
The only thing you can be sure of is that the construction and allocation of a
will be before b
. As long as you separate your statements with ;
, they'll be executed in order, regardless of optimization.
volatile
will not change that, what it does is preventing the compiler from caching the values between the accesses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With