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

2021-06-23 02:34:53 字數 1440 閱讀 8366

今天跟同事聊天,他說到stl

原始碼有用到顯示呼叫析構函式。試一了一下。果然能行。

#include

<

iostream

>

using

namespace

std;

class

myclass

~myclass()

};int

_tmain(

intargc, _tchar

*argv)

結果:

constructors

destructors        //這個是顯示呼叫的析構函式

destructors        // 這個是delete呼叫的析構函式

這有什麼用?

有時候,在物件的生命週期結束前,想先結束這個物件的時候就會派上用場了。

由此想到的:

因為我知道。

new的時候,其實做了兩件事,一是:呼叫malloc分配所需記憶體,二是:呼叫建構函式。

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

所以推測建構函式也是可以顯式呼叫的。做了個實驗。

int_tmain(

intargc, _tchar

*argv)

編譯pmyclass->myclass()出錯:

error c2273: 'function-style cast' : illegal as right side of '->'operator

天啊,它以為myclass是這個型別。

解決辦法有兩個:

第一:pmyclass

->

myclass::myclass();

第二:new

(pmyclass)myclass();

第二種用法涉及c++ placement new 的用法。

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

顯示呼叫建構函式有什麼用?

有時候,你可能由於效率考慮要用到malloc去給類物件分配記憶體,因為malloc是不呼叫建構函式的,所以這個時候會派上用場了。

另外下面也是可以的,雖然內建型別沒有建構函式。

int*i=

(int

*)malloc(

sizeof

(int

));new

(i)

int();

感覺這些奇奇怪怪的用法最好在寫**庫時,為了達到某個目時去使用,不推薦應用開發時使用。

答 、if(x>0.000001&&x

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

今天跟同事聊天,他說到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 這個是...

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

1.顯式呼叫析構函式 include using namespace std class myclass 輸出結果 constructor of myclass.destructor of myclass.顯式呼叫的析構函式 destructor of myclass.delete呼叫的析構函式 由...