Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
问题描述
我知道在 C++ 中为基类声明虚拟析构函数是一种很好的做法,但是即使对于用作接口的抽象类,声明 virtual
析构函数总是很重要吗?请提供一些原因和示例.
I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual
destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.
推荐答案
对于界面来说,这一点更为重要.你的类的任何用户都可能持有一个指向接口的指针,而不是一个指向具体实现的指针.当他们来删除它时,如果析构函数是非虚拟的,他们将调用接口的析构函数(或编译器提供的默认值,如果您没有指定),而不是派生类的析构函数.即时内存泄漏.
It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak.
例如
class Interface
{
virtual void doSomething() = 0;
};
class Derived : public Interface
{
Derived();
~Derived()
{
// Do some important cleanup...
}
};
void myFunc(void)
{
Interface* p = new Derived();
// The behaviour of the next line is undefined. It probably
// calls Interface::~Interface, not Derived::~Derived
delete p;
}
这篇关于为什么要在 C++ 中为抽象类声明虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么要在 C++ 中为抽象类声明虚拟析构函数?


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01