std :: enable_shared_from_this :: shared_from_this如何工作 [英] How std::enable_shared_from_this::shared_from_this works

查看:96
本文介绍了std :: enable_shared_from_this :: shared_from_this如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是不明白 std :: enable_shared_from_this :: shared_from_this 如何返回与现有指针共享所有权的共享pinter。换句话说,您

I just cannot understand how std::enable_shared_from_this::shared_from_this returns a shared pinter that shared ownership with existing pointer. In other words you do this:

std::shared_ptr<Foo> getFoo() { return shared_from_this(); }

所以当您呼叫 getFoo 时,确切地说,它得到与共享所有权的另一个 shared_ptr 是什么,而不是创建拥有相同所有权的单独的 shared_ptr

So when you call getFoo how does exactly it get what is the other shared_ptr to share the ownership with and not to create a separate shared_ptr that owns the same this.

我需要了解这一点,以便能够理解如何从所有增加的对象中创建shared_ptr相同的引用计数,并且不初始化单独的 shared_ptr s。

I need to understand this to be able to understand how to create shared_ptr from some object that all increase the same ref count and not initialize separate shared_ptrs.

推荐答案

enable_shared_from_this< T> 具有 weak_ptr< T> 数据成员。 shared_ptr< T> 构造函数可以检测 T 是否源自 enable_shared_from_this< T> 。如果是,则 shared_ptr< T> 构造函数将分配 * this (即 shared_ptr< T> )到 enable_shared_from_this< T> 中的 weak_ptr 数据成员。 shared_from_this()然后可以从 weak_ptr< T> <创建一个 shared_ptr< T>

enable_shared_from_this<T> has a weak_ptr<T> data member. The shared_ptr<T> constructor can detect if T is derived from enable_shared_from_this<T>. If it is, the shared_ptr<T> constructor will assign *this (which is the shared_ptr<T>) to the weak_ptr data member in enable_shared_from_this<T>. shared_from_this() can then create a shared_ptr<T> from the weak_ptr<T>.

可能的实现示例:

template<class D>
class enable_shared_from_this {
protected:
    constexpr enable_shared_from_this() { }
    enable_shared_from_this(enable_shared_from_this const&) { }
    enable_shared_from_this& operator=(enable_shared_from_this const&) {
        return *this;
    }

public:
    shared_ptr<T> shared_from_this() { return self_.lock(); }
    shared_ptr<T const> shared_from_this() const { return self_.lock(); }

private:
    weak_ptr<D> self_;

    friend shared_ptr<D>;
};

template<typename T>
shared_ptr<T>::shared_ptr(T* ptr) {
    // ...
    // Code that creates control block goes here.
    // ...

    // NOTE: This if check is pseudo-code. Won't compile. There's a few
    // issues not being taken in to account that would make this example
    // rather noisy.
    if (is_base_of<enable_shared_from_this<T>, T>::value) {
        enable_shared_from_this<T>& base = *ptr;
        base.self_ = *this;
    }
}

这篇关于std :: enable_shared_from_this :: shared_from_this如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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