Question on Smart Pointer example in the book

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • Question on Smart Pointer example in the book


      I have a question on a smart pointer example given in GCC 4 on page 74 (Chapter 3 Coding Tidbits and Style that Saved Me),
      under the section of smart pointer abuses.

      The example is:

      "The other gotcha is constructing two smart pointers to manage a single object:"

      Source Code

      1. int *z = new int;
      2. shared_ptr<int> bad1(z);
      3. shared_prt<int> bad2(z);

      I thought that smart pointers are useful precisely for this purpose.
      The z object now has 2 references to it and it will only be destroyed if its reference count drops to 0.

      Hence, I am confused why is this considered as a bad practice?
    • Yes and no.
      The purpose of the shared_ptrs is of course to avoid manual reference counting,
      but it does not work this way.

      What your code is doing is construct two independent smart_ptrs, and therefore two independent reference counters.
      You won't have two counters at 2, but 2 independent counters which know of exactly one reference.
      What happens now when the bad1 and bad2 are destroyed is why this is not only a bad practice, but actually a serious mistake:
      bad1 is destroyed, the destructor is called, since there are now no more references to z (it only knew 1 reference, namely itself), and hence z is deallocated.
      The same then happens for bad2, and z will be deallocated.. again. Though at this point there will be only garbage at z, which is the problem.

      What you actually want to do instead is of course to have two reference counters at 2.
      Doing this is as simple as

      Source Code

      1. int *z = new int;
      2. shared_ptr<int> a (z);
      3. shared_ptr<int> b = a;

      I hope that helps.