[LC++]STL Iterators and integers

Mark Phillips mark at austrics.com.au
Wed Aug 8 11:06:05 UTC 2001


Davide Bolcioni wrote:

> > There's one important reason to avoid deriving classes from STL containers
> > - AFAIK no STL container defines virtual destructor. This basically means
> > that you can't ensure proper destruction of such a derived container.
> > Unfortunately, I haven't read Thinking in C++, so I can't really comment
> > on that.
> 
> 
> class DerivedVector: public std::vector { ... }
> 
> DerivedVector * dv = new DerivedVector; // ...
> std::vector * vp = dvp;
> 
> delete vp; //  ~DerivedVector() is not called, just ~vector().
> 
> The problem is obvious in the above code, but is much less obvious in real
> code where new and delete are far away ... and to my knowledge, there is
> no way to guard against it

Is this a serious flaw in the design of STL???  Or is a non-virtual
destructor needed in STL for some important reason??

It means that the only safe way to "inherit" from an STL class is 
to include it as a member and then just "mimic" all the functionality
of the STL class in your own.  This is doable, but a lot of work, and
does away with the whole point of having inheritance capability!

> - except refusing to derive from a class
> which does not define a virtual destructor except in very controlled
> circumstances (where you're sure the above scenario does not occur, or
> you're sure the derived destuctor has really nothing to do and never
> will).

So as long as I only add functions to derived classes, not data, I 
should be fine.  And of course, as long as I don't --- down the track ---
inherit from my existing inherited class and add data.

This indicates to me a potential problem with C++.  You only need to
use the virtual keyword once (in the base class say), so further along
the tree of inheritance, if there is no keyword "virtual", you don't
know whether it is virtual or not --- you have to trace back through
the inherited classes to see.

Cheers (and thanks!)

Mark.



More information about the tuxCPProgramming mailing list