Search code examples
c++templatesg++gcc-warningeffective-c++

Is this a bug in my code or in g++'s analysis of -Weffc++?


I'm getting a warning thrown by -Weffc++ which appears to be wrong. I could use a second pair of eyes to confirm:

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;
}

The warning is:

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;

Tested with g++ (GCC) 4.9.3.

UPDATE

Added an additional class to provide an implementation example. The warning is correct pre se but I think my disagreement is for the warning to appear on a pure virtual function as it's meant to be an interface for another class.

@Frerich Raabe has provided the necessary clarification as to why g++ thinks I'm violating the rules set by Effective C++ and I've accepted this answer.

To silence the warning I have added the following:

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

Solution

  • The compiler is correct. Your operator++ reimplementation should return a value of the same type as *this, i.e. a some_class<...>. In fact, many implementations of operator++() end in

    return *this;
    

    See the section labelled 'Unary arithmetic operators' in this answer for a more elaborate discussion.