• 为什么一般要定义析构函数为虚析构函数


    没有使用虚析构函数可能会出现的问题:

    #include <iostream>
    #include <string>
    using namespace std;
    
    class A {
    public:
    	A() { cout << "A constructor" << endl; }
    	~A() { cout << "A destructor" << endl; }
    };
    
    class B: public A {
    	char *buf;
    public:
    	B() { buf = new char[10]; cout << "B constructor" << endl; }
    	~B() { cout << "B destructor" << endl; }
    };
    
    int main()
    {
    	A *p = new B;
    	delete p;  // p是基类类型指针,仅调用基类析构函数,造成B中申请的10字节内存没被释放。
    	return 0;
    }
    
    

    输出:

    A constructor
    B constructor
    A destructor

    解决:将基类中的析构函数定义为虚析构函数

    #include <iostream>
    #include <string>
    using namespace std;
    
    class A {
    public:
    	A() { cout << "A constructor" << endl; }
    	virtual ~A() { cout << "A destructor" << endl; }
    };
    
    class B: public A {
    	char *buf;
    public:
    	B() { buf = new char[10]; cout << "B constructor" << endl; }
    	~B() { cout << "B destructor" << endl; }
    };
    
    int main()
    {
    	A *p = new B;
    	delete p; //A中的析构函数说明为虚析构函数后,B中析构函数自动成为虚析构函数,由于P
                      //指向派生类对象,因此会调用派生类B的析构函数。
    	return 0;
    }
    
    

    输出:

    A constructor
    B constructor
    B destructor
    A destructor

  • 相关阅读:
    简单爬虫架构解析
    三种urllib实现网页下载,含cookie模拟登陆
    MySQL 从入门到删库
    Python Set
    Python dict
    Python tuple
    Python List
    死锁问题
    线程通信之生产者和消费者案例
    多线程安全和线程同步
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2858785.html
Copyright © 2020-2023  润新知