基类与接口类中的虚析构函数(virtual destructor)
2015-04-03 18:35
190 查看
一般情况下,在基类或者接口类中添加虚析构函(virtual destructor)数非常重要。原因很简单,就是想让析构的顺序从继承类开始往上开始一步步析构直到基类。
看例子吧:
首先,接口类不写虚析构函数
去调用测试一下:
当执行
时,程序并不会调用Foo类中的析构函数(因为你没在基类中写虚析构函数),所以造成内存泄露。
下面我们加上virtual destructor
看例子吧:
首先,接口类不写虚析构函数
// virtual d'tor // In base class or interface, it is important that add a virtual destructor class IFoo { public: virtual void dosomething() = 0; }; class Foo : public IFoo { public: Foo(int* pInt = NULL) : pInt(pInt){} virtual void dosomething() { pInt = new int[10]; pInt[1] = 1; pInt[2] = 2; } ~Foo() { delete[] pInt; } int* get_pInt() { return pInt; } const int* get_pInt() const { return pInt; } private: int* pInt; };
去调用测试一下:
using namespace std; int main() { IFoo* f = new Foo(); f->dosomething(); delete f; return 0; }
当执行
delete f;
时,程序并不会调用Foo类中的析构函数(因为你没在基类中写虚析构函数),所以造成内存泄露。
下面我们加上virtual destructor
class IFoo { public: virtual void dosomething() = 0; virtual ~IFoo(){} // add virtual destructor }; class Foo : public IFoo { public: Foo(int* pInt = NULL) : pInt(pInt){} virtual void dosomething() { pInt = new int[10]; pInt[1] = 1; pInt[2] = 2; } ~Foo() { delete[] pInt; } int* get_pInt() { return pInt; } const int* get_pInt() const { return pInt; } private: int* pInt; }; using namespace std; int main() { IFoo* f = new Foo(); f->dosomething(); delete f; // It's ok!!! return 0; }
相关文章推荐
- PHP中用接口、抽象类、普通基类实现“面向接口编程”与“耦合方法”简述
- 只在多态基类中声明虚析构函数
- (一) 两个接口(IPullToRefresh、ILoadingLayout)与一个基类(PullToRefreshBase)
- [置顶] 虚析构函数? vptr? 指针偏移?多态数组? delete 基类指针 内存泄漏?崩溃?
- C++ 虚函数、纯虚函数、抽象类、接口、虚基类
- C#中基类、派生类以及使用接口来实现多重继承
- C++ 继承特性的小探讨——基类虚析构函数
- C++学习笔记-----存在多态调用时,为基类定义虚析构函数
- C#中接口通过基类或派生类对方法的调用
- 条款07:为多态基类声明虚析构函数
- C++中基类的析构函数为什么要用virtual虚析构函数
- 接口与基类
- Java类中子类和基类的构造代码块,静态代码块、子类构造函数,基类构造函数的执行顺序
- [置顶] 虚析构函数? vptr? 指针偏移?多态数组? delete 基类指针 内存泄漏?崩溃?
- Eclipse重构时,自动添加基类或接口中的方法
- 结合.net框架在C#派生类中触发基类事件及实现接口事件
- C#虚基类继承与接口的区别 (转载)
- 对于基类添加虚析构函数问题
- 为什么基类中的析构函数要声明为虚析构函数?
- jscriptFrame(2) 使用Class基类定义接口