簡體   English   中英

完成操作后,是否需要告訴智能指針

[英]Do you need to tell Smart Pointers when you are done with them

使用智能指針,是否仍然需要釋放/重置它們以確保釋放內存? 還是可以讓它們超出范圍?

類成員智能指針的行為是否有所不同-與釋放內存,懸空指針有關? 析構函數應該始終釋放這些變量嗎?

class Foo
{
public:
    Foo()
    {
        myUPtr = std::unique_ptr<int>(new int);
        mySPtr = std::shared_ptr<int>(new int);
    }

    ~Foo()
    {
        // Should these smart pointers be released? Or will falling out of scope/deletion release the memory?
        myUPtr.release();
        mySPtr.reset();
    }

private:
    std::unique_ptr<int> myUPtr;
    std::shared_ptr<int> mySPtr;
};

int main()
{
    // When each of the below variables fall out of scope is there any difference in memory release? 
    Foo f;
    std::unique_ptr<Foo> uFoo(new Foo);
    std::shared_ptr<Foo> sFoo(new Foo);
    std::unique_ptr<int> uPtr(new int);
    std::shared_ptr<int> sPtr(new int);

    // Will all these smart pointers be released automatically? 
    // No need to call .release()/.reset() on any member and non-member smart pointers?

    return 0;
}

您是否仍需要釋放/重置它們以確保釋放內存?

沒有

還是可以讓它們超出范圍?

析構函數應該始終釋放這些變量嗎?

沒有

使智能指針如此智能和強大的原因之一是,您不再需要擔心手動管理內存。

僅供參考, std::unique_ptr::release實際上將減輕智能指針的職責:它返回原始指針,然后您需要對其進行手動管理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM