The Potential Pitfall of Deriving from C STL Containers
The practice of deriving from C Standard Library (STL) containers has been a subject of debate, with some arguing against its use. Despite perceived advantages, such as overloading functions and enabling specialization, there are potential risks associated with this approach.
The absence of virtual destructors in STL containers poses a significant hazard. When deriving a class from a STL container that lacks a virtual destructor, the derived class may not be able to properly handle polymorphic behavior. This can lead to unexpected results, especially when objects of derived classes are stored in containers and accessed through base class pointers.
To illustrate, consider the following scenario:
#include <vector> void kill_it(std::vector<double> *victim) { delete victim; // Invokes non-virtual ~std::vector<>() } typedef std::vector<double> Rates; class Charges: public std::vector<double> { }; int main() { std::vector<double> *p1, *p2; p1 = new Rates; p2 = new Charges; // Possible error introduced by user code kill_it(p2); kill_it(p1); return 0; }
In this example, the kill_it function does not have any knowledge of the derived class Charges. Consequently, it will invoke the non-virtual destructor of the base class std::vector
Another potential issue with deriving from STL containers arises from Microsoft's implementation of the vector class. In this implementation, the vector class itself is implemented through inheritance, with vector<> publicly derived from _Vector_Val<>. This adds an extra layer of complexity and potential hazards when working with derived classes.
While there may be advantages to using inheritance in certain scenarios, the benefits often come with increased complexity and potential risks. Composition, using a container as a member variable rather than a base class, is generally preferred for clarity and to avoid the potential issues associated with derivation.
The above is the detailed content of Should You Inherit from C STL Containers?. For more information, please follow other related articles on the PHP Chinese website!