std::enable_shared_from_this::shared_from_this 的工作原理
How std::enable_shared_from_this::shared_from_this works
我只是无法理解如何 std::enable_shared_from_this::shared_from_this
returns 一个与现有指针共享所有权的共享 pinter。换句话说,你做 this:
std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
因此,当您调用 getFoo
时,它究竟是如何获得另一个 shared_ptr
来共享所有权的,而不是创建一个拥有相同 [=] 的单独 shared_ptr
16=].
我需要理解这一点才能理解如何从某个对象创建 shared_ptr,这些对象都增加相同的引用计数而不初始化单独的 shared_ptr
s。
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>
可能的实施示例:
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
returns 一个与现有指针共享所有权的共享 pinter。换句话说,你做 this:
std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
因此,当您调用 getFoo
时,它究竟是如何获得另一个 shared_ptr
来共享所有权的,而不是创建一个拥有相同 [=] 的单独 shared_ptr
16=].
我需要理解这一点才能理解如何从某个对象创建 shared_ptr,这些对象都增加相同的引用计数而不初始化单独的 shared_ptr
s。
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>
可能的实施示例:
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;
}
}