如何使用weak_ptr构造一个保存对父级的引用的对象?

发布于 2025-01-04 18:36:00 字数 108 浏览 0 评论 0原文

假设我有一个对象,其中包含子对象的shared_ptr。

我希望子对象对父对象有一个weak_ptr,子对象的构造函数应该是什么样子以及如何从父对象构造子对象?

提前致谢

Say I have an object that contains a shared_ptr to a child object.

I want the child object to have a weak_ptr to the parent object, what should the child object's constructor look like and how should I construct a child from the parent?

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

‖放下 2025-01-11 18:36:00

由于您拥有子对象的唯一所有权,因此可以保证子对象的寿命不会比其父对象的寿命长。你可以有一个像这样的模型。

struct Parent;

struct Child {
        Child( Parent& p ) : p_(&p) {}
        Parent* p_;
};

#include <memory>

struct Parent {
        std::unique_ptr<Child> c_;
        void AddChild() {
                c_.reset(new Child(*this));
        }
};

当然,子级在析构函数中对父级所做的任何事情都应该小心,它可能会因为其父级超出范围而被销毁。这是子级对其父级拥有 weak_ptr 的唯一优势(它仍然无法从析构函数中对父级执行任何操作,但至少它可以安全地告诉我们这一点),但是这个依赖于其父级由 shared_ptr 拥有,这对于子级来说是一种更加不灵活的设计。

这将是 weak_ptr 解决方案:

// NOT RECOMMENDED
#include <memory>

struct Parent;

struct Child {
        Child( const std::shared_ptr<Parent>& p ) : p_(p) {}
        std::weak_ptr<Parent> p_;
};

struct Parent : std::enable_shared_from_this<Parent> {
        std::unique_ptr<Child> c_;
        void AddChild() {
                // Warning, undefined behaviour if this Parent
                // isn't owner by shared_ptr
                c_.reset(new Child(shared_from_this()));
        }
};

As you have unique owner ship of child objects the child is guaranteed not to outlive it's parent. You could have a model something like this.

struct Parent;

struct Child {
        Child( Parent& p ) : p_(&p) {}
        Parent* p_;
};

#include <memory>

struct Parent {
        std::unique_ptr<Child> c_;
        void AddChild() {
                c_.reset(new Child(*this));
        }
};

Of course, the child should be careful with anything that it does with the parent in the destructor, it might be being destroyed because its parent is going out of scope. This is about the only advantage of a child having a weak_ptr to its parent (it still won't be able to do anything with the parent from its destructor but at least it can safely tell that) but this relies on its parent being owned by a shared_ptr which is a much more inflexible design for the child.

This would be the weak_ptr solution:

// NOT RECOMMENDED
#include <memory>

struct Parent;

struct Child {
        Child( const std::shared_ptr<Parent>& p ) : p_(p) {}
        std::weak_ptr<Parent> p_;
};

struct Parent : std::enable_shared_from_this<Parent> {
        std::unique_ptr<Child> c_;
        void AddChild() {
                // Warning, undefined behaviour if this Parent
                // isn't owner by shared_ptr
                c_.reset(new Child(shared_from_this()));
        }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文