gpt4 book ai didi

c++ - std::enable_shared_from_this::shared_from_this 如何工作

转载 作者:IT老高 更新时间:2023-10-28 22:34:59 27 4
gpt4 key购买 nike

我只是无法理解 std::enable_shared_from_this::shared_from_this 如何返回与现有指针共享所有权的共享 pinter。换句话说,你做 this :

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

因此,当您调用 getFoo 时,它究竟是如何获得另一个 shared_ptr 以共享所有权而不是创建单独的 shared_ptr 拥有相同的this

我需要理解这一点才能理解如何从某个对象创建 shared_ptr,这些对象都增加相同的引用计数,而不是初始化单独的 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> )到 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;
}
}

关于c++ - std::enable_shared_from_this::shared_from_this 如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34061515/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com