简体   繁体   English

完成操作后,是否需要告诉智能指针

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

With smart pointers, are you still required to release/reset them to ensure the memory is released? 使用智能指针,是否仍然需要释放/重置它们以确保释放内存? Or is it ok to let them fall out of scope? 还是可以让它们超出范围?

Is there any difference in behaviour - relating to releasing memory, dangling pointers - for class member smart pointers? 类成员智能指针的行为是否有所不同-与释放内存,悬空指针有关? Should the destructor always release these variables? 析构函数应该始终释放这些变量吗?

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;
}

are you still required to release/reset them to ensure the memory is released? 您是否仍需要释放/重置它们以确保释放内存?

No 没有

Or is it ok to let them fall out of scope? 还是可以让它们超出范围?

Yes

Should the destructor always release these variables? 析构函数应该始终释放这些变量吗?

No 没有

One of the things that makes smart pointers so smart and powerful is that you no longer need to worry about manually managing the memory. 使智能指针如此智能和强大的原因之一是,您不再需要担心手动管理内存。

FYI, std::unique_ptr::release will actually relieve the smart pointer of its duty: it returns a raw pointer, which you then need to manually manage. 仅供参考, std::unique_ptr::release实际上将减轻智能指针的职责:它返回原始指针,然后您需要对其进行手动管理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM