Will a shared_ptr automatically free up memory?

北城以北 提交于 2019-12-01 03:41:36

问题


I need to use a shared_ptr here because I can't change the API.

Foo1 *foo1 = new Foo1(...);
shared_ptr<Foo2> foo2(foo1);

Is the shared_ptr here going to handle freeing the memory used by foo1? If I understand correctly, I shouldn't have to call delete on foo1 correct?


回答1:


Yes. You are correct, but the correct way to initialise foo2 is:

std::shared_ptr<Foo2> foo2 = std::make_shared<Foo1>();  

Herb Sutter discusses the reasons why you should use std::make_shared<>() here: https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/




回答2:


You shouldn't call delete on foo1.

Better you shouldn't create foo1. Only foo2:

shared_ptr<Foo2> foo2(new Foo1(...));
  • std::shared_ptr: http://en.cppreference.com/w/cpp/memory/shared_ptr

std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer.

If you do not need this pointer to be shared - consider to use std::unique_ptr

  • std::unique_ptr: http://en.cppreference.com/w/cpp/memory/unique_ptr

std::unique_ptr is a smart pointer that: retains sole ownership of an object through a pointer, and destroys the pointed-to object when the unique_ptr goes out of scope.




回答3:


Correct. The smart pointers provide ownership semantics. In particular, the semantics provided by std::shared_ptr are such that the object will be deleted once the last shared_ptr pointing to it is destroyed. shared_ptr keeps a reference count (how many shared_ptrs are referring to the object) and when it reaches 0, it deletes the object.



来源:https://stackoverflow.com/questions/12713004/will-a-shared-ptr-automatically-free-up-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!