Boost :: shared_ptr use_count

I am trying to understand what is going on in the following code. When object-a is deleted, does the shared_ptr member-b object remain in memory because object-c contains the shared_ptr for object-b?

    class B
    {
    public:
       B(int val)
       {
          _val = val;
       }
       int _val;
    };

    class A
    {
    public:
       A()
       {
          _b = new B(121);
       }
       boost::shared_ptr<B> _b;
    };

    class C
    {
    public:
       C()
       {
       }

       void setRef( boost::shared_ptr<B> b)
       {
          _b = b;
       }
       boost::shared_ptr<B> _b;
    };

    int main()
    {
       C c;
       {
          A *a = new A();       
          cout << "a._b.use_count: " << a->_b.use_count() << endl;
          c.setRef(a->_b);
          cout << "a._b.use_count: " << a->_b.use_count() << endl;
                  delete a;
       }
       cout << c._b->_val << endl;
    }

      

0


a source to share


3 answers


The object A

will be cleared as soon as it A

is removed at the end of its block. But the shared_ptr it contains was subsequently copied, increasing the reference count.

So the object B

will have a reference count of 2 after c.setRef

(which is referenced by the object A

and the C

-object shared_ptr

). When A

removed at the end of its block, the object's reference count B

drops to again 1

, since only C

shared_ptr is referring to it now.

After being C

destroyed at the end of main, it shared_ptr

will also be destroyed as part of the destruction C

, and now, when the reference count drops to zero, the object with the pointer to B

will be destroyed shared_ptr

.



So, reference counting for the B

-object:

0: before existence of a.
1: from start of lifetime of a until c.setRef
2: from c.setRef until copy of its parameter
3: from copy of c.setRef' parameter until return of it
2: from return of c.setRef until end of a' block
1: from end of a' block until end of main
0: after main returned (object doesn''t exist anymore now)

      

+1


a source


No, when a is deleted, a -> _ b (the pointer itself) ceases to exist.



An object which points a -> _ b will continue to exist because c._b still points to it.

+2


a source


The target shared_ptr

will remain active until the final link to it is removed. In this case, it will happen when the instance C

goes out of scope.

0


a source







All Articles