Home >Backend Development >C++ >Should You Derive from C STL Containers?

Should You Derive from C STL Containers?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 13:46:13478browse

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, instead of the destructor of the derived class, Rates. This can lead to problems if the derived class contains additional resources that need to be cleaned up during destruction.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn