Boost logo

Boost :

From: Gennadiy Rozental (gennadiy.rozental_at_[hidden])
Date: 2005-10-26 10:32:18


>>>>> I have read a few times that people sometimes wish that std::vector
>>>>> (or other containers) had a virtual destructor. [snip]
>>>>> This allows one to write something like:
>>>>>
>>>>> struct person {
>>>>> string first_name;
>>>>> string last_name;
>>>>> };
>>>>> class people : public virtual_vector<person>
>>>>> {
>>>>> public:
>>>>> //extra methods
>>>>> };
>>>>>
>>>>> Is this useful?
>>>>
>>>> unless I mis-read (or mis-understood...far more likely) a lot of
>>>> books on how C++ works, I don't believe there is any reason for what
>>>> _you've_ shown to need a virtual destructor.
>>>
>>> You have mis-read or mis-understood (or you need better books).
>>> Consider: virtual_vector<person>* p = new people;
>>
>> I guees I wasn't clear.. I was suggesting that virtual_vector has no
>> need for existence.
>>
>>> delete p;
>>> That invokes undefined behaviour unless virtual_vector<person> has a
>>> virtual destructor.
>>
>> are you suggesting that if it were class people: public
>> std::vector<person> {.....}; as above the same would be true?
>> not "in practice", "in theory".
>
> Absolutely. See 5.3.5/1 of the standard where this is explicitly called
> out
> as undefined behaviour.

Yes, it you are trying to delete pointers to 'people' through base class you
do need virtual destructor. But:

1. In general in bad idea to inherit from STL container. Most probably you
need a different relatationship (hint: containment)
2. If you insist on inheritance you still in most cases wouldn't need
virtual destructor: don't delete through pointers on vector. To reinforce
this you could employ either private inheritance or protected destructor in
wrapper around vector.

In any case this is not a type of idiom anyone need to promote.

Gennadiy


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk