delete释放内存,改为先调用子类析构,再调用基类析构

This commit is contained in:
huihut 2018-04-04 01:27:46 +08:00
parent d91abf8e8c
commit d495d620d8

View File

@ -180,7 +180,7 @@ int main()
Base *ptr = new Derived(); Base *ptr = new Derived();
ptr->who(); ptr->who();
// 因为Base有虚析构函数virtual ~Base() {}所以delete调用基类Base析构函数也调用派生类Derived)析构函数,防止内存泄漏。 // 因为Base有虚析构函数virtual ~Base() {}所以delete会先调用派生类Derived析构函数再调用基类Base)析构函数,防止内存泄漏。
delete ptr; delete ptr;
ptr = nullptr; ptr = nullptr;
@ -533,7 +533,7 @@ int main()
{ {
Shape * shape1 = new Circle(4.0); Shape * shape1 = new Circle(4.0);
shape1->calcArea(); shape1->calcArea();
delete shape1; //因为Shape有虚析构函数所以delete释放内存时调用基类析构函数,也调用子类析构函数 delete shape1; //因为Shape有虚析构函数所以delete释放内存时先调用子类析构函数,再调用基类析构函数,防止内存泄漏
shape1 = NULL; shape1 = NULL;
return 0 return 0
} }