Question

I'm trying to understand what's going on in the following code. When object-a is deleted, does it's shared_ptr member variable object-b remains in memory because object-c holds a shared_ptr to 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;
    }
Was it helpful?

Solution

The A-object will be cleaned up as soon as a is deleted at the end of its block. But the shared_ptr it contains was subsequently copied, incrementing its reference count.

Thus, the B-object will have a reference count of 2 after c.setRef (referenced by the A-object and by the C-object's shared_ptr). When a is deleted at the end of its block, then the reference count of the B-object drops to 1 again since only c's shared_ptr is referencing it now.

After c is destroyed at the end of main, its shared_ptr will be destroyed too as part of c's destruction, and now as the reference count drops to zero, the pointed-to B object will be deleted by shared_ptr.

So, the reference counts of 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''s parameter until return of it
2: from return of c.setRef until end of a''s block
1: from end of a''s block until end of main
0: after main returned (object doesn''t exist anymore now)

OTHER TIPS

No, when a is deleted, a->_b (the pointer itself) will cease to exist.

The object that a->_b points to will continue to exist, because c._b still points to it.

The target of the shared_ptr will remain live until the final reference to it is deleted. In this case, this will be when the C instance goes out of scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top