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?
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/
You shouldn't call delete on foo1.
Better you shouldn't create foo1. Only foo2:
shared_ptr<Foo2> foo2(new Foo1(...));
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With