C++ 什么时候调用析构函数

析构函数是在对象消亡时,自动被调用,用来释放对象占用的空间。

有四种方式会调用析构函数:

1.生命周期:对象生命周期结束,会调用析构函数。

2.delete:调用delete,会删除指针类对象。

3.包含关系:对象Dog是对象Person的成员,Person的析构函数被调用时,对象Dog的析构函数也被调用。

4.继承关系:当Person是Student的父类,调用Student的析构函数,会调用Person的析构函数。

第一种 生命周期结束

#include <iostream>
using namespace std;
class Person{
public:
    Person(){
        cout << "Person的构造函数" << endl;
    }
    ~Person()    {
        cout << "删除Person对象 " << endl;
    }
private:
    int name;
};

int main() {
    Person person;
    return 0;
}

结果

Person的构造函数
删除Person对象

第二种 delete

对于new的对象,是指针,其分配空间是在堆上,故而需要用户删除申请空间,否则就是在程序结束时执行析构函数

#include <iostream>
using namespace std;
class Person{
public:
    Person(){
        cout << "Person的构造函数" << endl;
    }
    ~Person()    {
        cout << "删除Person对象 " << endl;
    }
private:
    int name;
};

int main() {
    Person *person=new  Person();
    delete person;
    return 0;
}

结果

Person的构造函数
删除Person对象

第三种 包含关系

#include <iostream>
using namespace std;
class Dog{
public:
    Dog(){
        cout << "Dog的构造函数" << endl;
    }
    ~Dog()    {
        cout << "删除Dog对象 " << endl;
    }
private:
    int name;
};
class Person{
public:
    Person(){
        cout << "Person的构造函数" << endl;
    }
    ~Person()    {
        cout << "删除Person对象 " << endl;
    }
private:
    int name;
    Dog dog;
};


int main() {
    Person person;
    return 0;
}

结果

Dog的构造函数
Person的构造函数
删除Person对象
删除Dog对象

第四种 继承关系

#include <iostream>
using namespace std;

class Person{
public:
    Person(){
        cout << "Person的构造函数" << endl;
    }
    ~Person()    {
        cout << "删除Person对象 " << endl;
    }
private:
    int name;

};
class Student:public Person{
public:
    Student(){
        cout << "Student的构造函数" << endl;
    }
    ~Student()    {
        cout << "删除Student对象 " << endl;
    }
private:
    int name;
    string no;
};

int main() {
    Student student;
    return 0;
}

结果

Person的构造函数
Student的构造函数
删除Student对象
删除Person对象

参考:https://blog.csdn.net/chen134225/article/details/81221382

原文地址:https://www.cnblogs.com/AntonioSu/p/12269474.html