析构函数
当类的对象撤销时,析构函数被隐式调用。析构函数不是释放内存,而是释放内存前进行扫尾工作。
对象何时撤销?1,静态分配的,生存期过后撤销。2,动态分配的,delete时撤销。
析构函数的命名 ~类型( ),析构函数没有形参和返回值。
一个类只能有一个析构函数,如果程序员不显示的提供析构函数,编译器提供默认的析构函数。
为包含动态分配的内存的类和使用系统资源的类构造适合的析构函数。
动态内存管理
//Cat.h #include<string> #include<iostream> class Cat { private:std::string name;int age; public:Cat() {name = "huahua";age = 0;}Cat(const std::string &name,int age) {this->name = name;this->age = age;}~Cat() {std::cout << name << "析构...\n";} };
#include<string> #include<cstdlib> #include"Cat.h" using namespace std; int main() {double *ptr = new double(3.14);delete ptr;//释放单个变量,deleteptr = nullptr;//必须置为nullptrint *arr = new int[10]();//()的意思默认初始化,基本数据类型初始化为0,bool初始化false,//指针nullptr,对象调用默认构造函数delete[] arr;//释放数组delete[]arr = nullptr;Cat *c1 = new Cat("mimi", 1);delete c1;Cat *catArr = new Cat[3]();delete[] catArr;catArr = nullptr;system("pause");return 0; }
mimi析构...
huahua析构...
huahua析构...
huahua析构...
请按任意键继续. . .