当你用完它们时你需要告诉智能指针吗
Do you need to tell Smart Pointers when you are done with them
有了智能指针,还需要release/reset保证内存释放吗?或者让它们超出范围是否可以?
class 成员智能指针在释放内存、悬挂指针方面的行为是否有任何差异?析构函数是否应该始终释放这些变量?
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
实际上会解除智能指针的职责:它 returns 一个原始指针,然后您需要手动管理它。
有了智能指针,还需要release/reset保证内存释放吗?或者让它们超出范围是否可以?
class 成员智能指针在释放内存、悬挂指针方面的行为是否有任何差异?析构函数是否应该始终释放这些变量?
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
实际上会解除智能指针的职责:它 returns 一个原始指针,然后您需要手动管理它。