使用优化器构建和销毁局部变量 [英] Local variables construction and destruction with optimizer involved
问题描述
如果我有此代码:
class A { ... };
class B { ... };
void dummy()
{
A a(...);
B b(...);
...
}
我知道变量 a 和
b
将以反向分配顺序销毁( b
,然后 a
);但是我可以确定优化器永远不会交换 a
和 b
的分配和构造?或者我必须使用 volatile
才能执行它吗?
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?
推荐答案
是任何可观察的副作用(即读取和写入 volatile
对象和调用I / O函数) a
的任何副作用以及
a
的任何副作用, b
需要在需要之前发生。
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.
很难想象为什么你需要更严格的排序但是使对象 volatile
将确保 a
在初始化 b
,但是在 a
完成之前,构造函数中的一些代码仍可能发生。
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.
这篇关于使用优化器构建和销毁局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!