shared_ptr增加父引用
shared_ptr increase parent reference
伪代码:
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;
};
我想用shared_ptr来管理A和B的指针,B是A的孩子。当对孩子有强烈的参考时,父母A不能被摧毁。
问题是当 B 引用增加时,如何增加父项 A 的引用计数。
B
可以将shared_ptr<A>
作为其父级作为成员,但 is 将创建一个引用循环,使得两个引用计数都不会减少到 0。要打破循环,请使用 weak_ptr
.
我已经解决了这个问题,代码如下:
#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 %dn", 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,
相关文章:
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- 为什么我的代码在输出中增加了93天
- std::thread 增加 DLL 引用计数,从而防止卸载 DLL
- 作为赋值(增加引用变量)C++的左操作数所需的左值
- C++为什么原始指针不会增加shared_ptr的引用计数?
- 从工厂方法返回的ComPtr的引用计数增加两次
- 如何引用其他类中的函数以向量增加价值
- shared_ptr:在基类的shared_ptr中复制时,引用计数是否增加
- 在不增加引用计数的情况下迭代共享指针的映射
- 如果使用引用传递对象,则会增加引用计数类中的引用计数
- shared_ptr增加父引用
- IDispatch::Invoke(DISPATCH_PROPERTYGET)是否增加返回的IDispatch接口的引用
- 我可以使用cmpxchg16b自动地将指针复制到指针和int,同时增加int(原子引用计数)
- 添加对共享ptr的引用会增加引用计数吗?