12

我刚刚在 GCC 中遇到了以下警告:

warning: implicit dereference will not access object of type ‘volatile util::Yield’ in statement [enabled by default]

在编译此代码时:

volatile util::Yield y1;
util::Yield y2;
y1 += y2; // <--- Warning triggered here.

不幸的是,我不太明白 GCC 试图告诉我什么......

Yield 类声明如下:

class Yield {
public:
    Yield();

    Yield &operator+=(Yield const &other);
    Yield &operator+=(Yield const volatile &other);
    Yield volatile &operator+=(Yield const &other) volatile;
    Yield volatile &operator+=(Yield const volatile &other) volatile;

    // Other operators snipped...
};

有任何想法吗?

谢谢!

4

1 回答 1

9

来自 GCC 手册,第 6.1 节 - 何时访问易失性对象?

当使用对 volatile 的引用时,G++ 不会将等效表达式视为对 volatile 的访问,而是发出警告,指出没有访问 volatile。这样做的基本原理是,否则很难确定发生易失性访问的位置,并且不可能忽略返回易失性引用的函数的返回值。同样,如果您希望强制读取,请将引用转换为右值。

The warning stems from the fact that the += operator returns a reference to a volatile object, and that the expression 'y1 += y2' ignores that return value. The compiler is letting you know that the reference will not actually be dereferenced (i.e. the volatile value will not be read).

于 2012-12-13T22:31:57.120 回答