Risks of Deriving from C STL Containers
Despite the potential advantages of deriving classes from C STL containers, such as function overloading, template specialization, and improved debugging, there are inherent risks associated with this approach.
Consider the following example:
#include <vector> class Rates : public std::vector<double> { }; class Charges : public std::vector<double> { }; int main() { auto p1 = new Rates; auto p2 = new Charges; kill_it(p2); // User code that knows nothing about Rates or Charges kill_it(p1); return 0; }
The kill_it function deletes victim's memory while executing the non-virtual destructor of std::vector
The problem arises if the user inadvertently introduces errors in the kill_it function's ??? section. For example, if the user modifies p2 to point to a Rates object before calling kill_it(p2), the non-virtual destructor of std::vector
To mitigate this risk, it is generally recommended to use composition instead of derivation when handling STL containers. Composition allows for a more flexible and less error-prone approach.
The above is the detailed content of Should You Inherit from C STL Containers: Risks and Alternatives?. For more information, please follow other related articles on the PHP Chinese website!