std::enable_shared_from_this::shared_from_this 的工作原理

问题描述 投票:0回答:1

我只是无法理解

std::enable_shared_from_this::shared_from_this
如何返回与现有指针共享所有权的共享指针。换句话说,你这样做这个

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

因此,当您调用

getFoo
时,它到底如何获得另一个
shared_ptr
来共享所有权,而不是创建一个拥有相同
shared_ptr
的单独
this

我需要理解这一点才能理解如何从某个对象创建shared_ptr,这些对象都会增加相同的引用计数而不是初始化单独的

shared_ptr

c++ c++11 shared-ptr
1个回答
43
投票

enable_shared_from_this<T>
有一个
weak_ptr<T>
数据成员。
shared_ptr<T>
构造函数可以检测
T
是否派生自
enable_shared_from_this<T>
。如果是,则
shared_ptr<T>
构造函数会将
*this
(即
shared_ptr<T>
)分配给
weak_ptr
中的
enable_shared_from_this<T>
数据成员。然后
shared_from_this()
可以从
shared_ptr<T>
创建
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.