delete this的問題

來源:互聯網
上載者:User
TEST1:#include <iostream>
using namespace std;

class Base
{
public:
    virtual ~Base()
    { 
        cout << "Base dtor!" << endl;
    }
};

class Derived : public Base
{
private:
    virtual ~Derived()
    { 
        cout << "Derived dtor!" << endl;
    }
};

int main()
{
    Derived* pd=new Derived;
    //delete pd;     //error,相當於調用pd->~Derived()
    Base* pb=new Derived;
    delete pb;

    return 0;
}

/*
* Base的dtor可見,雖然會被virtual到Derived的dtor上去,這就是所謂的dynamic binding可以突破存取權限,其實存取權限本來就是只有在編譯期起作用的,想清楚編譯期和運行時其實很容易理解上面代碼

*/

TEST2:#include <iostream>
using namespace std;

class Base 

public:
    void destroy() //偽析構
    {
        cout << "DTOR"<< endl;
        delete this;
    }

private: 
    ~Base() {} 
};

int main()
{
    Base *pb = new Base;//ok
    pb->destroy();

    Base b;             //error: "cannot access private member declared in class 'Base'"
    b.destroy();

    return 0;
}

/*
   不論是靜態或是普通成員函數都是可以通過delete或delete this刪掉這樣的一個對象。
   這種私人dtor加上剛才說的偽析構的成員函數可以達到只允許new來建立對象執行個體,
   而不允許直接定義執行個體的效果。
 */

/*因為b 是局部變數(auto),所以生命期末會調用解構函式,而解構函式為private*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.