【问题标题】:GCC warning about implicit dereferenceGCC 关于隐式取消引用的警告
【发布时间】:2012-12-13 22:06:13
【问题描述】:

我刚刚在 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...
};

有什么想法吗?

谢谢!

【问题讨论】:

  • 这个警告对于 c++11 来说应该是过时的,因为在 c++11 中函数调用的左值将不再被读取。
  • @JohannesSchaub-litb:已经有几年了,但我仍然在 C++14 中收到此警告(目前在 GCC 最新版本中对此感到沮丧)。我想知道是否有更深层次的需要,或者它只是一个遗物。最近的 clang 没有给出这样的警告,但似乎从来没有这样做过,查看 Godbolt 中的旧版本。

标签: c++ gcc gcc-warning


【解决方案1】:

来自 GCC 手册,Section 6.1 - When is a Volatile Object Accessed?

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

警告源于 += 运算符将 reference 返回到 volatile 对象,而表达式 'y1 += y2' 忽略了该返回值。编译器让您知道该引用实际上不会被取消引用(即不会读取 volatile 值)。

【讨论】:

  • 如果您不想强制读取,如何编写代码以避免出现警告?
  • @BenVoigt:void operator=(Yield const &amp; other) volatile;
  • 完全没有返回值并不是一个好的解决方案。如果它在某些情况下使用而不在其他情况下使用怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 2022-06-27
  • 2012-12-19
相关资源
最近更新 更多