2019-06-14 C++ Destructor

For both user-defined or implicitly-defined destructors, after the body of the destructor is executed, the compiler calls the destructors for all non-static non-variant members of the class, in reverse order of declaration, then it calls the destructors of all direct non-virtual base classes in reverse order of construction (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases.

在Destructor調(diào)用完成后,成員的Destructor調(diào)用前,this的狀態(tài)是這樣的:


image.png

如果在析構(gòu)成員B時,使用了成員A,那么需要手動獲取A的指針,而不是使用this捕獲。因為這時的this已經(jīng)是失效的了:

std::shared_ptr<A> dump_a = this->a;
this->b = std::shared_ptr<B>(this->a->CreateB(),
    [this, dump_a](B* p)
    {
        dump_a->ReleaseB(p); // OK
        this->a->ReleaseB(p); // Error
    });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容