Advice on a better way to extend C++ STL container with user-defined methods

This is a bad idea.

There are a lot of reasons you shouldn’t derive from STL classes, foremost of which is that they’re not designed for it. Vector doesn’t have a virtual destructor, so if you extend it, the superclass’s destructor may not be called properly and you’ll get memory leaks.

For more on this, see this answer on why not to derive from std::string. Many of the same points apply:

Constructor doesn’t work for class inherited from std::string

  • No virtual destructor
  • No protected functions (so you gain nothing by inheriting)
  • Polymorphism won’t work, and you’ll get object slicing. std::vector is assignable, but if you add your own fields they won’t get copied on assignment if you assign from a vector pointer or vector reference. This is because vector‘s operator= does not know about your fields.

For all of these reasons, you’re better off making utility functions than extending when it comes to STL.

Leave a Comment