6

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?

Justin
  • 447
  • 4
  • 10
  • 33
  • 3
    Yes, you're correct - that's the whole point of `shared_ptr`. I don't understand why you're not using `shared_ptr = new Foo1` though. – Mark Ransom Oct 03 '12 at 16:43
  • 1
    When the `shared_ptr`'s reference count hits 0, it will destruct the `Foo1` object it holds, but if you allocate memory in the `Foo1` object, you have to make sure the destructor behaves as you expect. – wkl Oct 03 '12 at 16:43
  • 1
    How are the types Foo1 and Foo2 related? There had better be a valid conversion between the two. – Martin York Oct 03 '12 at 17:04

3 Answers3

13

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/

Mark Ingram
  • 71,849
  • 51
  • 176
  • 230
  • Note that this also discusses reasons to **not** use `std::make_shared`. – Pete Becker Oct 03 '12 at 16:50
  • I've updated the link to point to Herb Sutter's GotW#103 instead, as that gives a better breakdown of what the function actually does. – Mark Ingram Oct 03 '12 at 16:55
  • The original link had a more complete analysis of when to use and **when not to use** `std::make_shared`. The new link only says that `std::make_shared` is wonderful. – Pete Becker Oct 03 '12 at 17:29
  • 1
    Herb Sutter's link has been updated. Here's the new permanent link: https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/ – RAM Jun 18 '18 at 11:43
4

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.

PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
1

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.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324