Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a shared_ptr automatically free up memory?

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?

like image 708
Justin Avatar asked Oct 03 '12 16:10

Justin


2 Answers

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/

like image 177
Mark Ingram Avatar answered Oct 21 '22 03:10

Mark Ingram


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.

like image 34
PiotrNycz Avatar answered Oct 21 '22 05:10

PiotrNycz