如何在C ++中维护一个指向父对象的弱指针? [英] How to maintain a weak pointer to a parent in C++?

查看:149
本文介绍了如何在C ++中维护一个指向父对象的弱指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中的子对象中是否有一个标准的方法来维护一个指向父对象(使用共享指针创建)的弱指针?

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;
};

在上面的类B的所有实例都需要保存一个弱指针到它们的父对象A类)。使用shared_ptr实例化A类对象。我可以想到一个使用null删除程序的解决方案。

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?

推荐答案

有一个隐式转换为weak_ptr,所以你可以使用

There is an implicit conversion to weak_ptr, so you can use

void SetParentPtr(boost::weak_ptr<A> a) { }

直接。

检查boost :: shared_from_this,以便父对象可以给自己指针,一个weak_ptr显式。

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.

这篇关于如何在C ++中维护一个指向父对象的弱指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆