5

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?

4

4 回答 4

6

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.

于 2011-03-10T09:54:15.630 回答
3

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.

于 2011-03-10T09:39:58.190 回答
0

Ok, I find such statements in standard but I am a little confused by other's answer.

Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function. (In other words, function executions do not interleave with each other.)

It only ensures function calling do not interleave with each other, but the functions are indeterminately sequenced, meaning that,

Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which.

于 2011-03-10T09:42:41.057 回答
0

I faced with the problem. An optimizer reordered a code. To prevent reordering I would recommend two ways:

1) Incapsulate your objects inside a structrure:

class A { ... };
class B { ... };

struct C {
     A a;
     B b;
};

void dummy()
{
    C c;
}

2) Put variables inside block operators:

class A { ... };
class B { ... };

void dummy()
{
    A a;
    {
        B b;
    }
}
于 2020-02-25T21:24:50.503 回答