顯式呼叫建構函式和析構函式

2021-07-01 19:02:56 字數 1099 閱讀 8148

1.顯式呼叫析構函式

#include using namespace std;

class myclass

輸出結果:

constructor of myclass.

destructor of myclass.          // 顯式呼叫的析構函式

destructor of myclass.          // delete呼叫的析構函式

由以上結果可以看出,new的時候做了兩件事,一是呼叫malloc分配所需記憶體,二是呼叫建構函式

delete的時候也做了兩件事,一是呼叫析構函式,二是呼叫free釋放記憶體

正常情況下析構函式只會被呼叫一次,如果被呼叫兩次,而析構函式內有delete的操作,會導致記憶體釋放兩次的錯誤。

顯式呼叫析構函式的作用:有時候,在物件的生命週期結束之前,想先結束這個物件時就可以派上用場。

2.顯式呼叫建構函式一

#include using namespace std;

class myclass

輸出constructor of myclass

3.顯式呼叫建構函式二(placement new)

#include using namespace std;

class myclass

輸出結果:

constructor of myclass

destructor of myclass

placement new的作用就是:建立物件(呼叫該類的建構函式)但是不分配記憶體,而是在已有的記憶體塊上面建立物件。用於需要反覆建立並刪除的物件上,可以降低分配釋放記憶體的效能消耗。

關於placement new不用delete刪除物件的說明:placement new並不分配記憶體,只是返回指向已經分配好的某段記憶體的乙個指標。因此不能刪除它,但需要呼叫物件的析構函式。

顯式呼叫建構函式的作用:有時候,可能會考慮到效率而使用malloc給類物件分配記憶體,因為malloc不呼叫建構函式,這時候就派上用場了

參考:

顯式呼叫建構函式和析構函式

今天跟同事聊天,他說到stl 原始碼有用到顯示呼叫析構函式。試一了一下。果然能行。include iostream using namespace std class myclass myclass int tmain intargc,tchar argv 結果 constructors destr...

顯式呼叫建構函式和析構函式

stl 原始碼中有用到顯示呼叫析構函式。試一了一下。果然能行。include iostream using namespace std class myclass myclass int tmain intargc,tchar argv 結果 constructors destructors 這個是...

顯式呼叫建構函式和析構函式

今天跟同事聊天,他說到stl 原始碼有用到顯示呼叫析構函式。試一了一下。果然能行。include iostream using namespace std class myclass myclass int tmain intargc,tchar argv 結果 constructors destr...