std::enable_shared_from_this<T>::enable_shared_from_this
自 C++11 起
constexpr enable_shared_from_this() noexcept; (1)
enable_shared_from_this( const enable_shared_from_this<T>&obj ) noexcept; (2)
构造一个新的 enable_shared_from_this 对象。私有的 std::weak_ptr<T>
成员被值初始化。
参数
obj
- 一个要复制的 enable_shared_from_this
备注
没有移动构造函数:从派生自 enable_shared_from_this 的对象进行移动不会转移其共享身份。
示例
#include <memory>
struct Foo : public std::enable_shared_from_this<Foo> {
Foo() {} // implicitly calls enable_shared_from_this constructor
std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
int main() {
std::shared_ptr<Foo> pf1(new Foo);
auto pf2 = pf1->getFoo(); // shares ownership of object with pf1
}