Reputation: 25938
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;
}
Upvotes: 0
Views: 342
Reputation: 7111
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.
Upvotes: 5