Search code examples
c++optimizationvolatileallocationdestruction

Local variables construction and destruction with optimizer involved


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?


Solution

  • 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.