Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 759
Loghorn Avatar asked Mar 10 '11 09:03

Loghorn


2 Answers

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.

like image 72
Mike Seymour Avatar answered Nov 15 '22 10:11

Mike Seymour


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.

like image 44
littleadv Avatar answered Nov 15 '22 10:11

littleadv