指向所有者类 [英] Pointer to owner class

查看:190
本文介绍了指向所有者类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

授予一个从自己的类型管理其子类的类,每个子类都有一个指针返回其父类。

Granted a class that manages its children from its own type, with each children having a pointer back to its parent.

class Class {
    std::array<std::shared_ptr<Class>, 4> children;
    std::weak_ptr<Class> parent;
}

A weak_ptr 像上面的代码,不工作,因为它必须通过共享ptr初始化。

A weak_ptr, like in the code above, does not work, because it has to be initialized through a shared ptr.

void initChild() {
    subtrees[0] = std::make_shared<Class>(std::shared_ptr<Class>(this));
}

这将明显删除 this 并导致错误。

This would obviously delete this and result in an error.

有没有可能有一个弱的引用父,而不使用原始的指针只有选项?

Is there any possibility to have a weak reference to the parent without using raw pointers, or would that be the only option?

推荐答案

如果你使用父指针作为一个可观察成员(即不是必须分配/销毁的东西) ,一个原始指针是唯一的出路。

If you are using the parent pointer as an observable member (i.e. NOT something that must be allocated/destroyed), a raw pointer is the only way to go.

这篇关于指向所有者类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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