码迷,mamicode.com
首页 > 其他好文 > 详细

virtual析构函数的作用

时间:2016-06-15 19:11:59      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

析构函数是为了在对象不被使用之后释放它的资源,虚函数是为了实现多态。那么把析构函数声明为vitual有什么作用呢?,下面通过例子来说明一下vitual的用途。

using namespace std;

class Base
{
public:
  Base() {};     //Base的构造函数
  ~Base()        //Base的析构函数
  {
    cout << "the destructor of class Base!" << endl;
  };
  virtual void DoSomething() 
  {
    cout << "Do something in class Base!" << endl;
  };
};
    
class Derived : public Base
{
public:
  Derived() {};     //Derived的构造函数
  ~Derived()      //Derived的析构函数
  {
    cout << "the destructor of class Derived!" << endl;
  };
  void DoSomething()
  {
    cout << "Do something in class Derived!" << endl;
  };
};
    
int main()
{
  Derived *pTest1 = new Derived();   //Derived类的指针
  pTest1->DoSomething();
  delete pTest1;
    
  cout << endl;
    
  Base *pTest2 = new Derived();      //Base类的指针
  pTest2->DoSomething();
  delete pTest2;
    
  return 0;
}


先看程序输出结果:
1       Do something in class Derived!
2       the destructor of class Derived!
3       the destructor of class Base!
4      
5       Do something in class Derived!
6       the destructor of class Base!

从运行结果来看,pTest1运行比较正常,也好理解,pTest2运行了子类的Do something和父类的析构函数,并没有运行子类的析构函数,这样会造成内存泄漏。

pTest2运行了子类的Do something量因为父类的Do something加了virtual。

pTest2运行了父类的析构函数是因为父类的析构函数并没有加virtual,所以它并不会运行子类的析构函数。

如果Base的析构函数加上virtual,那么pTest1和pTest2运行过程一样。

总结:如果一个类有可能会被继承,那么它的析构函数最好加上virtual,不然出现内存泄漏问题找都找不到。

virtual析构函数的作用

标签:

原文地址:http://www.cnblogs.com/zhangnianyong/p/5588483.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!