zoukankan      html  css  js  c++  java
  • 虚析构函数

    #include <iostream>
    using namespace std;
    
    class A {
    public:
    	A() { cout << "call A()" << endl; }
    	~A() { cout << "call ~A()"; }
    };
    
    class B:public A {
    	char *buf;
    public:
    	B() { buf = new char[100]; cout << "call B()" << endl; }
    	~B() { delete []buf; cout << "call ~B()" << endl; }
    };
    
    int main(void)
    {
    	A *p = new B;
    	delete p;
    
    	return 0;
    }
    
    

    输出:

    call A()
    call B()
    call ~A()

    并没有调用~B(),  从而导致100字节的内存没有被释放。

    将A的析构函数说明为虚函数可解决此问题。

    #include <iostream>
    using namespace std;
    
    class A {
    public:
    	A() { cout << "call A()" << endl; }
    	virtual ~A() { cout << "call ~A()"; }
    };
    
    class B:public A {
    	char *buf;
    public:
    	B() { buf = new char[100]; cout << "call B()" << endl; }
    	~B() { delete []buf; cout << "call ~B()" << endl; }
    };
    
    int main(void)
    {
    	A *p = new B;
    	delete p;
    
    	return 0;
    }
    
     
    输出:

    call A()
    call B()
    call ~B()
    call ~A()

  • 相关阅读:
    新手silverlight练习五子棋( 二 )
    VS注释模板工具
    NET简介
    MS Sql server 总结(命令恢复)
    Highcharts入门(一)
    jqGrid入门(1)
    WIN7常见问题汇总
    log4net入门
    DLL管理工具
    C++回顾1 简介
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2841099.html
Copyright © 2011-2022 走看看