如何正确地从析构函数不是虚拟的基类继承? [英] How to correctly inherit from a base class whose destructor is not virtual?
问题描述
我想从类A继承,但是A的析构函数不是虚拟的,因此我无法修改A的定义.如何避免以下情况?
I want to inherit from class A, but A's destructor is not virtual and I cannot modify A's definition. How to avoid the following case?
struct A
{
A()
: a(new char[8])
{}
~A()
{
delete[] a;
}
char* a;
}
struct B : A
{
B()
: A(), b(new char[8])
{}
~B()
{
delete[] b;
}
char* b;
};
int main()
{
A* p_a = new B;
delete p_a; // How to avoid such a dangerous deletion?
}
推荐答案
如果基类没有虚拟析构函数,并且您无法修改类定义,那么您很不走运.根据一般经验,您可能不应该将公共继承与没有虚拟析构函数的基类一起使用.
If the base class doesn't have a virtual destructor and you can't modify the class definition, you're pretty much out of luck. As a general rule of thumb, you probably shouldn't use public inheritance with a base class that doesn't have a virtual destructor.
也许您可以尝试使用合成而不是继承?将A
的实例放在B
中,并提供用于包装对A
成员函数的调用的公共成员函数.
Maybe you can try using composition instead of inheritance? Place an instance of A
in B
, and provide public member functions that wrap calls to member functions of A
.
这篇关于如何正确地从析构函数不是虚拟的基类继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!