5

According to this defect report C++03 Standard does not guarantee that in the following code:

volatile int x;
void f() {
    x;
}

the variable is read from.

Then how do I write code that just read the volatile variable value and discards the result (read for the sake of read)?

4

1 回答 1

5

int i = x;应该管用。此代码绝对需要读取 volatile 变量,并且不允许优化器优化读取。但是由于该变量i未使用,优化器可以避免存储读取值所涉及的任何额外工作。

您可能还需要这样的东西来避免编译器警告:(void)i;

于 2012-12-19T10:44:10.233 回答