Re: Non-virtual destructors & valarray memory allocation
* Earl Purple:
Michael Hopkins wrote:
Hi all
A couple of questions that are influencing the design of some classes.
1) Why were the std:: library containers not given virtual destructors - is
this a feature or an oversight?
Feature. They don't need them as they have no other virtual methods so
how can you override any of their functionality anyway?
Sometimes the point of deriving from a class is only to extend.
At least one popular language even uses the keyword "extends" to
designate class derivation.
That said the lack of virtual destructors is only a problem if
dynamically allocated instances are destroyed polymorphically, which in
practice isn't much of a problem, especially compared to the much larger
& more serious other pitfalls one may stumble into when using C++.
We would like to derive publicly from them in a couple of cases and now have
to be more disciplined than we should need to be about how we use those
types.
There is no need to derive publicly from them. If you want to add extra
functionality then either:
1. create free-functions that take the collections as parameters
Consider constructors, notational consistency, introduction of virtual
member functions, interfaces, memory management, you name it.
After all, you are only going to use their public methods (there are no
protected ones and you won't have access to the private ones anyway).
Some standard library classes have protected members.
2. Create a class that uses aggregation, i.e. it contains the
collection you want and has extra functions. You can then allow users
to call all the original functions either by implementing them
yourself, providing an implicit conversion or (preferred) overloading
operator-> (operator. cannot be overloaded). The last of these will
automatically bring in all the behaviour you want without the dangers
of implicit conversion.
Consider e.g. downcasting.
Regarding the destruction issue, what are smart pointers for?
Essentially a smart pointer puts in place, or can put in place, the
equivalent of a virtual destructor.
Summing up, when deriving from a standard library class would be in
order except for the lack of virtual destructor, just derive, but don't
destroy polymorphically -- use smart pointers if that's an issue.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]