1

When compiling with -Weffc++ and extending boost::iterator_facade, I get the compiler warning: base class has a non-virtual destructor. What can I do to fix this?

Here is sample code:

#include <iostream>
#include <boost/iterator/iterator_facade.hpp>

struct my_struct_t {
  int my_int;
  my_struct_t() : my_int(0) {
  }
};

class my_iterator_t : public boost::iterator_facade<
                          my_iterator_t,
                          my_struct_t const,
                          boost::forward_traversal_tag
                         > {
  private:
  friend class boost::iterator_core_access;

  my_struct_t my_struct;

  public:
  my_iterator_t() : my_struct() {
  }

  void increment() {
    ++ my_struct.my_int;
  }

  bool equal(my_iterator_t const& other) const {
    return this->my_struct.my_int == other.my_struct.my_int;
  }

  my_struct_t const& dereference() const {
    return my_struct;
  }
};

int main() {
  my_iterator_t my_iterator;
  std::cout << my_iterator->my_int << "\n";
  ++my_iterator;
  std::cout << my_iterator->my_int << "\n";
  return 0;
}

I compile on Fedora 19 like this:

$ g++ test.cpp -std=gnu++0x -Weffc++ -o test

Here is the actual warning:

g++ test.cpp -std=gnu++0x -Weffc++ -o test
test.cpp:10:7: warning: base class ‘class boost::iterator_facade<my_iterator_t, const my_struct_t, boost::forward_traversal_tag>’ has a non-virtual destructor [-Weffc++]
 class my_iterator_t : public boost::iterator_facade<
       ^

Thanks.

Bruce
  • 53
  • 1
  • 4

1 Answers1

1

-Weffc++ option enables warnings about violations of the some style guidelines from Scott Meyers’ Effective C++ book. Your code violates the Item 7: Make destructors virtual in polymorphic base classes. So the compiler isn't complaining about your iterator, it's about the base class: boost::iterator_facade. I don't think you can eliminate the warning by modify your own code. As to why virtual destructor in polymorphic base classes are so important, a good answer is here.

Community
  • 1
  • 1
jfly
  • 7,715
  • 3
  • 35
  • 65
  • I can't imagine that Boost would create code that would force warnings in my code, leaving nothing I can do about it. I want to use -Weffc++, and I don't want the warning, and I am willing to not use boost::iterator_facade, if that is what it takes. – Bruce Jan 18 '14 at 17:54
  • Actually, it doesn't matter if polymorphism doesn't get involved. If your really care about the warning, derive your custom iterator from std::iterator instead of boost::iterator_facade. – jfly Jan 19 '14 at 06:02
  • Thanks for mentioning std::iterator. Unfortunately, std::iterator requires subclassing too. Compiling the [STL example](http://www.cplusplus.com/reference/iterator/iterator/) with -Weffc++ gives the same warning. I'll forego the benefits of traits management and just not subclass boost::iterator_facade or std::iterator. – Bruce Jan 19 '14 at 23:10