C 建構函式和析構函式的呼叫順序

2022-09-23 14:54:05 字數 1326 閱讀 9284

c++如果沒有分配資源那麼就不一定需要析構函式,否則就需要釋放資源,如下:

[cpp]  

class vector , sz ; // constructor: acquire memory  

˜vector() // destructor: release memory  

// ...  

private:  

double∗ elem; // elem points to an array of sz doubles  

int sz; // sz is non-negative  

};  

析構函式的呼叫順序是從底往上的:

[1] first, the constructor invokes its base class constructors,

首先,是呼叫該類的基類建構函式

[2] then, it invokes the member constructors, and

然後是該成員類的建構函式(重要記憶,有些書好像沒有提到)

[3] finally, it executes its own body.

最後才是本類的建構函式

而析構函式的呼叫順序剛好是相反

a destructor 『『tears down』』 an object in the reverse order:

[1] first, the destructor executes its own body,

首先呼叫本類的析構函式

[2] then, it invokes its member destructors, and

然後呼叫成員類的析構函式

[3] finally, it inv okes its base class destructors.

最後才是基類的析構函式

特別指出:虛基類是在其他任何類之前呼叫建構函式的,而在所有其他類之後呼叫析構函式的。

這樣的呼叫順序是為了保證基類或者成員類沒有在他們建立之前被呼叫,或者在析構之後還可能被呼叫。

建構函式根據宣告順序,執行成員類和基類的建構函式,而不是根據初始化列表(initializers)順序。

沒定義建構函式的時候,可以使用預設建構函式,定義了之後就會發生錯誤了,如下:

[cpp]  

struct s1 ;  

s1 x; // ok: x.s is initialized to ""  

struct x ;  

struct s2 ;  

s2 x1; // error :  

s2 x2 ; // ok: x2.x is initialized with 1  

C 建構函式析構函式呼叫順序

在使用建構函式和析構函式時,需要特別注意對它們的呼叫時間和呼叫順序。在一般情況下,呼叫析構函式的次序正好與呼叫建構函式的次序相反 最先被呼叫的建構函式,其對應的 同一物件中的 析構函式最後被呼叫,而最後被呼叫的建構函式,其對應的析構函式最先被呼叫。簡單來說,其建構函式的順序就一句話 基類建構函式 成...

C 建構函式和析構函式的呼叫順序

c 如果沒有分配資源那麼就不一定需要析構函式,否則就需要釋放資源,如下 class vector sz constructor acquire memory vector destructor release memory private double elem elem points to an ...

C 建構函式和析構函式的呼叫順序

析構函式的呼叫順序是從底往上的 1 first,the constructor invokes its base class constructors,首先,是呼叫該類的基類建構函式 2 then,it invokes the member constructors,and 然後是該成員類的建構函式...