Local variables construction and destruction with optimizer involved

五迷三道 提交于 2019-12-23 09:48:36

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5257768/local-variables-construction-and-destruction-with-optimizer-involved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!