gpt4 book ai didi

c++ - 当你用完它们时你需要告诉智能指针吗

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:09 26 4
gpt4 key购买 nike

有了智能指针,还需要release/reset来保证内存释放吗?或者让它们超出范围是否可以?

对于类成员智能指针,在释放内存、悬挂指针方面的行为是否有任何差异?析构函数是否应该始终释放这些变量?

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?

没有

Or is it ok to let them fall out of scope?

Should the destructor always release these variables?

没有

使智能指针如此智能和强大的原因之一是您不再需要担心手动管理内存。

仅供引用,std::unique_ptr::release实际上会解除智能指针的职责:它返回一个原始指针,然后您需要手动管理它。

关于c++ - 当你用完它们时你需要告诉智能指针吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34938945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com