[LC++]STL Iterators and integers

Davide Bolcioni 9odb6x3rfr001 at sneakemail.com
Thu Aug 9 06:12:47 UTC 2001


Mark Phillips mark at austrics.com.au [mltuxcpp/linux-cpp list] wrote:

>>
>>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 surely is a design choice: you do not pay the overhead of the vtable

pointer unless you have reason to. Overall, the STL promotes generic
programming (templates) over inheritance.

 
> 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.
Yes, but the problem is that noticing a slip from the self-imposed

discipline necessary to make sure the above conditions are met is hard

to track as the project gets large.


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

I usually follow this convention: I can only introduce a virtual 
function as an abstract method (the = 0 syntax). All implementations
of a virtual function must have the virtual keyword, for a reminder.
In this way, manual use of grep, sort and diff allows me to sort out
the odd cases.

Davide Bolcioni
-- 
There is no place like /home.




More information about the tuxCPProgramming mailing list