Home >Backend Development >C++ >Should You Derive from C STL Containers?
Potential Pitfall in Deriving from the C STL Containers
In the realm of C programming, there often arises a debate over the merits of deriving from the standard library's containers (containers that come with the C standard library, such as vectors, lists, etc.) or simply using typedefs to represent them (creating a new name for an existing type without defining a new type). While both approaches offer their advantages, it is crucial to be aware of a potential risk associated with deriving from STL containers.
When using derivation, it is essential to remember that the standard containers, such as vectors, do not declare their destructors as virtual. This means that if you derive from one of these containers and define a non-virtual destructor in your derived class, you will run into issues when attempting to destroy an object of that derived class using a pointer to the base class.
To illustrate this issue, consider the following example:
class Rates : public std::vector<double> { /* ... */ }; int main() { std::vector<double>* p = new Rates; delete p; // This will invoke the non-virtual ~std::vector<double>(), potentially leading to problems }
In this case, when the delete operator is called on the pointer p, it will invoke the destructor of the base class, std::vector
Therefore, while deriving from STL containers offers certain advantages, such as enabling function overloading and template specialization, it is crucial to exercise caution and ensure that you do not override the base class destructor with a non-virtual one. If you need polymorphic behavior, consider using composition instead of inheritance.
The above is the detailed content of Should You Derive from C STL Containers?. For more information, please follow other related articles on the PHP Chinese website!