析构函数,也叫析构器,对象在销毁的时候,会自动调用析构函数,一般用于完成对象的清理工作。
析构函数与类同名,以 ~
开头,没有返回值(void都不能写),不接受任何参数,不能被重载。所以,对于一个给定的类来说,只有唯一一个析构函数。
如果我们自己不写析构函数,编译器会生成一个默认的析构函数,其函数体为空 {}
,表示没干什么有意义的事。
构造函数、析构函数要声明为 public
才能被外界正常使用。
通过 malloc()/free() 分配和释放的对象不会调用其构造函数和析构函数。
#include <iostream>
using namespace std;
struct Person
{
int m_age;
Person()
{
cout << "Person::Person()" << endl;
}
~Person()
{
cout << "Person::~Person()" << endl;
}
void run()
{
cout << "Person::run() - " << m_age << endl;
}
};
int main()
{
Person* p = (Person*)malloc(sizeof(Person));
p->m_age = 10;
p->run();
free(p);
return 0;
}
通过 new/delete 分配和释放的对象会调用其构造函数和析构函数。
#include <iostream>
using namespace std;
struct Person
{
int m_age;
Person()
{
cout << "Person::Person()" << endl;
}
~Person()
{
cout << "Person::~Person()" << endl;
}
void run()
{
cout << "Person::run() - " << m_age << endl;
}
};
int main()
{
Person* p = new Person; // 构造函数被调用
p->m_age = 10;
p->run();
delete p; // 析构函数被调用
return 0;
}