[LC++]STL Iterators and integers

Mark Phillips mark at austrics.com.au
Thu Aug 9 12:15:07 UTC 2001


> 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.

I've been reading up on this issue, and my preliminary conclusions are:

In certain circumstances the idea of deriving classes from STL containers
is appealing.  For example, you might want to define a new form of vector
which has extra functionality.  You want it to _actually_ _be_ a vector
so that you can access it the way vectors can be accessed, and so that
STL algorithms can be applied to it.  As appealing as this is, the STL
is designed without virtual functions to make it more efficient.  This
means any class derivation you do must be done with much more care.  
There are several strategies for taking this care, as follows:

1. One way of overcomming the potential problems is to ensure that 
the STL container you derived from is never used as a base class.  By
this I mean that you never have a pointer to an STL container which
actually points to a derived class.  Either you don't deal in pointers,
or, when you do, you point directly to the derived class, not to the
STL class from which it was derived.  As long as you keep to this
(and perhaps have documentation to make this requirement clear) then
there should be no problems.

2. A slight relaxing of the above is possible.  You may _allow_
base class pointers, provided such pointers are _not_ _allowed_
to be used to delete the object.  They are used only for 
referring to the object.  With this relaxation it is even more
important, to document things properly to ensure things aren't
used incorrectly.

3. If the derived class doesn't define any new data, only 
providing extra functionality, and if only singular-inheritance
(not multiple) is involved, then base class pointers can be
used fine because the base class destructor will do the
right thing.

4. If none of the above approaches is suitable for the situation,
define a wrapper class which is basically a copy of the required
STL container, except defines the destructor (and anything else
needed) as virtual.  Then use the wrapper class as the base
class.


Well, I'm still fairly new and inexperienced with C++, but this
is what I've been able to glean from my reading so far.

Cheers,

Mark.



More information about the tuxCPProgramming mailing list