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()

  • 相关阅读:
    信息安全算法
    另类装载问题
    分治法快速排序
    动态规划最长公共子序列
    java网络编程1
    Jndi和会话bean
    EJB初探
    JSF初探
    简单计算器
    关于坐火车
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2841099.html
Copyright © 2011-2022 走看看