Home > Backend Development > C++ > Should You Inherit from C STL Containers: Risks and Alternatives?

Should You Inherit from C STL Containers: Risks and Alternatives?

DDD
Release: 2024-11-26 14:13:10
Original
1027 people have browsed it

Should You Inherit from C   STL Containers: Risks and Alternatives?

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;
}
Copy after login

The kill_it function deletes victim's memory while executing the non-virtual destructor of std::vector. This can lead to potential issues with Charges (the derived class) but not with Rates (the typedef).

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 will be called, resulting in incorrect behavior.

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template