一.背景
之前知道對象結束生命時,會自動調用析構函數.如果類中存在動態數組時,會在析構函數中會對動態數組對應的指針進行delete操作.不過一直對動態對象的delete操作和析構函數之間的關系沒有太多關注.直到最近在看delete這塊知識時,發現了這樣的表述
二.舉例
下面的代碼中,在main函數的#if 1中動態創建了對象t,然后對t的成員變量進行了賦值,最后進行了delete t的操作.最后的執行結果是:
//運行結果
Object Release
p Release
這里實際上是delete操作做完后,就直接調用了析構函數.
而#else中寫的是在棧中創建的對象t.該種情況下調用析構函數實際上是在main()函數的{}作用域結束后.
//實例代碼
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> using namespace std; class Test { public: Test() { } ~Test() { cout << "Object Release" << endl; if (p) { delete p; p = NULL; cout << "p Release" << endl; } } public: char *p; }; int main() { #if 1 Test *t = new Test(); t->p = new char[10]; strcpy(t->p, "hello"); delete t; #else Test t; t.p = new char[10]; strcpy(t.p, "hello"); #endif return 0; }