简体   繁体   English

如何在 class Hirarchy 中传递智能指针

[英]How to pass smart pointers in a class Hirarchy

So, im trying to figure out, how to pass pointers between objects in a Hirarchy of objects.因此,我试图弄清楚如何在对象层次结构中的对象之间传递指针。 The actual program im writing is a component based game engine, but i will try to break the problem down as far as possible.我写的实际程序是一个基于组件的游戏引擎,但我会尽量分解问题。

My Current Hirarchy look like this, i have 3 classes, a parent class, that basically governs the lifetime of all child objects, if it gets destructed, everything else will follow:我当前的层次结构看起来像这样,我有 3 个类,一个父类 class,它基本上控制着所有子对象的生命周期,如果它被破坏,其他一切都会随之而来:

Parent.h:

    class Parent
    {
    private:
        std::vector<std::shared_ptr<Object>> objects;
    };

A Middle Object, that governs the lifetime of its child objects:一个中间 Object,它控制其子对象的生命周期:

Object.h:

    class Object
    {
    public:
        Parent* parent;

    private:
        std::vector<std::shared_ptr<Child>> childObjects;
    };

And a Child Object:还有一个孩子 Object:

Child.h:

    class Child
    {
    public:

        std::weak_ptr<Object> parent;
    };

The problem is now, that the Child object needs a reference to its parent object, but all the shared pointers that own the Childs parent object live in the Global Parent and just creating a weak pointer from a pointer to the Childs Parent would not work.现在的问题是,子 object 需要对其父 object 的引用,但是拥有子父 object 的所有共享指针都存在于全局父中,并且不会从子父创建弱指针。

I've come up with two solutions, either passing a plain pointer to the Child and having the child traverse up to the Global parent and get the weak pointer there, which would require finding the pointer to the childs parent in a vector and might not always be possible.我提出了两种解决方案,要么将一个普通指针传递给 Child 并让孩子遍历到 Global parent 并在那里获取弱指针,这需要在向量中找到指向 childs parent 的指针,并且可能不会总是有可能的。

The other solution i have is passing a weak pointer to the childs parent constructor and storing a weak pointer to itself in the childs parent which does seem kinda messy.我的另一个解决方案是将一个弱指针传递给子父构造函数,并将一个指向自身的弱指针存储在子父级中,这看起来有点乱。

Im now asking if theres some better solution i have missed.我现在问我是否错过了一些更好的解决方案。

Thank you, shared_from_this was exactly what i was looking for.谢谢, shared_from_this正是我想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM