这是我的代码中的错误还是 g++ 对 -Weffc++ 的分析中的错误?
Is this a bug in my code or in g++'s analysis of -Weffc++?
我收到 -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
。
更新
添加了额外的 class 以提供实施示例。警告是 正确的 本身,但我认为我不同意警告出现在纯虚函数上,因为它本应成为另一个 class.[=14 的接口=]
@Frerich Raabe 提供了必要的说明,说明为什么 g++ 认为我违反了 Effective C++ 设定的规则,我接受了这个答案。
为了消除警告,我添加了以下内容:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
virtual class_type& operator++() = 0;
#pragma GCC diagnostic pop
编译器是正确的。您的 operator++
重新实现应该 return 与 *this
类型相同的值,即 some_class<...>
。事实上,operator++()
的许多实现都以
结尾
return *this;
有关更详细的讨论,请参阅 this answer 中标记为 'Unary arithmetic operators' 的部分。
我收到 -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
。
更新
添加了额外的 class 以提供实施示例。警告是 正确的 本身,但我认为我不同意警告出现在纯虚函数上,因为它本应成为另一个 class.[=14 的接口=]
@Frerich Raabe 提供了必要的说明,说明为什么 g++ 认为我违反了 Effective C++ 设定的规则,我接受了这个答案。
为了消除警告,我添加了以下内容:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
virtual class_type& operator++() = 0;
#pragma GCC diagnostic pop
编译器是正确的。您的 operator++
重新实现应该 return 与 *this
类型相同的值,即 some_class<...>
。事实上,operator++()
的许多实现都以
return *this;
有关更详细的讨论,请参阅 this answer 中标记为 'Unary arithmetic operators' 的部分。