考虑这段代码,
int some_int = 100;
while(some_int == 100)
{
//your code
}
当这个程序被编译时,编译器可能会优化这个代码,如果它发现程序从不尝试改变some_int
的值,所以它可能想通过将 while(some_int == 100)
更改为等效于 while 的 something 来优化 while
循环(true)
以便执行速度更快(因为 while
循环中的条件似乎总是 true
)。 (如果编译器没有优化它,那么它必须在每次迭代中获取 some_int
的值并将其与 100 进行比较,这显然有点慢。)
但是,有时(程序的某些部分的)优化可能不受欢迎,因为可能是其他人正在更改 some_int
从 的值>在编译器不知道的程序之外,因为它看不到它;但这就是你设计它的方式。在这种情况下,编译器的优化将不会产生预期的结果!
因此,为确保获得所需的结果,您需要以某种方式阻止编译器优化 while
循环。这就是 volatile
关键字发挥作用的地方。你需要做的就是这个,
volatile int some_int = 100; //note the 'volatile' qualifier now!
换句话说,我会这样解释:
volatile
告诉编译器,
"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"
嗯,这就是 volatile
阻止编译器优化代码的方式。现在搜索网络以查看一些示例。
引用 C++ 标准 ($7.1.5.1/8)
[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]
相关话题:
Does making a struct volatile make all its members volatile?
我是一名优秀的程序员,十分优秀!