解構函式什麼時候調用

來源:互聯網
上載者:User

建構函式的一個重要作用是為對象申請資源,相應地,解構函式要負責釋放這些資源。下面理解一下解構函式:

何時調用解構函式:(以下摘自《C++ Prime》Page 412)

撤銷類對象時會自動調用解構函式;變數在超出範圍時會自動撤銷;動態分配的對象只有在指向該隊向的指標被刪除時才撤銷;如果沒有刪除指向動態對象的指標,則不會運行該對象的解構函式,對象會一直存在,從而導致記憶體流失。PS:當對象的引用或者指標超出範圍時,不會運行解構函式。只有刪除指向動態指派至的指標或者實際對象(而不是對象的引用)超出範圍時,才會運行解構函式。

下面對這條規律進行考察:

 #include <string.h>#include <vector>#include <iostream>using namespace std;int i=0;int j=0;class CDemo{    public:        CDemo():str(NULL){cout<<"constructor_"<<i++<<endl;};        CDemo(const CDemo &cd){cout<<"constructor_"<<i++<<endl;this->str=new char[strlen(cd.str)+1];strcpy(str,cd.str);};        ~CDemo(){cout<<"destrcutor_"<<j++<<endl;if(str) delete []str;};        char *str;};int main(){    CDemo *pDemo=new CDemo();    cout<<"R1"<<endl;    {        CDemo d1;        CDemo &d2=d1;        d2.str=new char[32];        strcpy(d2.str,"hello wordl");    }    cout<<"R2"<<endl;    pDemo->str=new char[32];    strcpy(pDemo->str,"this is pDemo2");    delete pDemo;}

程式輸出結果

constructor_0R1constructor_1destructor_0R2destructor_1

符合上述規律。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.