我已经解决了这个问题,代码如下:
#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;
}
输出:
a ref 1
a ref 2, b1 ref 2,
a ref 3, b1 ref 3,
a ref 4, b1 ref 4,