【问题标题】:Is this a bug in my code or in g++'s analysis of -Weffc++?这是我的代码中的错误还是 g++ 对 -Weffc++ 的分析中的错误?
【发布时间】:2016-02-12 14:05:57
【问题描述】:

我收到了一个由 -Weffc++ 抛出的警告,这似乎是错误的。我可以用第二双眼睛来确认:

template<template<class> class CLASS_TYPE, typename T>
class some_class
{
typedef CLASS_TYPE<T> class_type;

public:
   virtual ~some_class() {};
   virtual class_type& operator++() = 0;
};

template<typename T>
class other_class
:
public some_class<other_class, T>
{
public:
   virtual ~other_class() {};
   other_class<T>& operator++() {
      return *this;
   };
};

int main() {

   return 0;
}

警告是:

main.cpp:8:39: warning: prefix ‘some_class<CLASS_TYPE, T>::class_type& some_class<CLASS_TYPE, T>::operator++()’ should return ‘some_class<CLASS_TYPE, T>&’ [-Weffc++]
    virtual class_type& operator++() = 0;

g++ (GCC) 4.9.3测试。

更新

添加了一个额外的类来提供一个实现示例。警告是正确本身,但我认为我不同意警告出现在纯虚函数上,因为它是另一个类的接口。

@Frerich Raabe 提供了必要的说明,解释了为什么 g++ 认为我违反了 Effective C++ 设置的规则,并且我已经接受了这个答案。

为了使警告静音,我添加了以下内容:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
virtual class_type& operator++() = 0;
#pragma GCC diagnostic pop

【问题讨论】:

  • CLASS_TYPE&lt;T&gt;some_class&lt;CLASS_TYPE, T&gt; 是同一类型吗?我希望some_class&lt;CLASS_TYPE, T&gt; 会被退回。
  • 您要求确认编译器报告该代码的警告? Confirmed。你有理由相信编译器是错的吗?你什么都没说。
  • 添加了额外的说明。

标签: c++ templates g++ gcc-warning effective-c++


【解决方案1】:

编译器是正确的。您的operator++ 重新实现应该返回与*this 相同类型的值,即some_class&lt;...&gt;。其实operator++()的很多实现都以

结尾
return *this;

有关更详细的讨论,请参阅this answer 中标有“一元算术运算符”的部分。

【讨论】:

  • 你是对的,但我不同意的是出现在纯虚函数上的警告。我想你是对的,warning 是有效的;这是警告而不是错误。
猜你喜欢
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 2020-06-17
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多