如何在 C++ 中维护指向父级的弱指针?
是否有一种标准方法可以在 C++ 的子对象中维护指向父对象(使用共享指针创建)的弱指针?
本质上,我需要实现以下内容:
Class B;
Class A
{
...
private:
B m_b;
};
Class B
{
....
public:
void SetParentPtr(const boost::shared_ptr<A>& a)
{
m_parentPtr = a;
}
private:
boost::weak_ptr<A> m_parentPtr;
};
在上面的所有 B 类实例中,都需要保存一个指向其父级(即 A 类的对象)的弱指针。 A 类对象是使用shared_ptr 实例化的。 我可以想到一个使用空删除器的解决方案。 但这是做类似事情的标准方法吗?
Is there a standard way of maintaining a weak pointer to a parent (which is created using a shared pointer) in a child object in C++?
Essentially, I need to implement something on the lines of the following:
Class B;
Class A
{
...
private:
B m_b;
};
Class B
{
....
public:
void SetParentPtr(const boost::shared_ptr<A>& a)
{
m_parentPtr = a;
}
private:
boost::weak_ptr<A> m_parentPtr;
};
In the above all instances of class B need to hold a weak pointer to their parent (i.e object of class A). Class A objects are instantiated using a shared_ptr. I can think of a solution that uses a null deleter. But is that a standard way of doing something like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有隐式转换为weak_ptr,所以可以
直接使用。
还要检查 boost::shared_from_this ,以便父级可以给自己一个指针,而无需显式存储weak_ptr。
否则,这似乎是拥有后向指针的正常方式。 只需检查使用反向指针是否有真正的附加值即可。
There is an implicit conversion to weak_ptr, so you can use
directly.
check also boost::shared_from_this so the parent can give a pointer to himself without storing a weak_ptr explicitly.
Otherwise, this seems like a normal way to have a back-pointer. Just check whether there is a real added value in using back-pointers.
我会尝试做这样的事情:
I would try to do something like this:
weak_ptr
和shared_ptr
明确支持您上面所做的事情,当您尝试时会发生什么? 更准确地说,执行您正在做的操作,不使用 null 删除器,然后根据需要使用weak_ptr
上的标准行为将其转换为shared_ptr
:What you are doing above is explicitly supported by
weak_ptr
andshared_ptr
, what happens when you try it? To be more precise, do what you are doing, without the null deleter, and then you use the standard behaviour on theweak_ptr
to convert it to ashared_ptr
as needed: