0

pseudo code :

typedef shared_ptr<B> ptr_child;
typedef shared_ptr<A> ptr_parent ;
class A
{
public:
    A()
    {
        child = ptr_child(new B);
    }

    ptr_child getB()
    {
        return child;
    }
private:
    ptr_child child;
};

I want to use shared_ptr to manage pointer of A and B. B is A's child. And when have strong reference to child, parent A can't be destroyed.

Question is how to increase reference count of parent A when when B reference increased.

Nolan Hyde
  • 212
  • 2
  • 8
  • Please give a concrete example that illustrates the problem. – Cheers and hth. - Alf Nov 15 '14 at 04:40
  • `parent` and `child`(`child` may has `child` too) are all manage by shared_ptr. Some one may hold a reference of a `child`, and it's `parent` has been destroyed. My problem is when have reference to `child`, `parent` should not be destroyed. – Nolan Hyde Nov 15 '14 at 05:53
  • THe question then is, who owns the `parent`, when/how is it eventually destroyed? (For example, a collection of `shared_ptr` instances that point to the same object, collectively own that object.) – Cheers and hth. - Alf Nov 15 '14 at 20:32

2 Answers2

0

B can hold a shared_ptr<A> to its parent as a member, though is will create a reference cycle such that neither reference count will decrease to 0. To break the cycle, use a weak_ptr.

Sam Miller
  • 23,808
  • 4
  • 67
  • 87
  • If B hold a weak_ptr of it's parent A, when strong reference of A is 0(destroyed) and strong reference of B count not 0, B's parent weak_ptr will expire. My goal is when strong reference of B > 0, A cant be destroyed. – Nolan Hyde Nov 15 '14 at 05:35
0

I have solved the problem, code as follow:

#include <memory>

class B;
class A;

typedef std::shared_ptr<A> a_ptr;
typedef std::shared_ptr<B> b_ptr;
class B
{
public:
    B(A* prt):parent(prt){}

private:    
    A* parent;
};

class A : public std::enable_shared_from_this<A>
{
public:
    A(){}
    b_ptr getChild()
    {
        b_ptr pb = b_ptr(this->shared_from_this(), child);
        return pb;
    }

    static a_ptr getA()
    {
        a_ptr pa = a_ptr(new A);
        pa->child = new B(pa.get());
        return pa;
    }

private:
    B* child;
};

int wmain(int argc, wchar_t* argv[])
{
    a_ptr a = A::getA();
    printf("a ref %d\n", a.use_count());
    b_ptr b1 = a->getChild();
    printf("a ref %d, b1 ref %d, \n", a.use_count(), b1.use_count());
    b_ptr b2 = a->getChild();
    printf("a ref %d, b1 ref %d, \n", a.use_count(), b1.use_count());
    b_ptr b3 = b2;
    printf("a ref %d, b1 ref %d, \n", a.use_count(), b1.use_count());

    //A and B are share reference, when no reference to A, but have reference to B, A will not be destroyed.

    return 0;
}

output:

a ref 1
a ref 2, b1 ref 2,
a ref 3, b1 ref 3,
a ref 4, b1 ref 4,
Nolan Hyde
  • 212
  • 2
  • 8