1. 程式人生 >實用技巧 >其它 >delete物件時會自動呼叫類的解構函式

delete物件時會自動呼叫類的解構函式


一.背景

之前知道物件結束生命時,會自動呼叫解構函式.如果類中存在動態陣列時,會在解構函式中會對動態陣列對應的指標進行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; }