-
- std::enable_shared_from_this
使能shared_from_this.它是在派生类中使能成员函数shared_from_this的基类。
该类提供了允许派生类的对象可以创建shared_ptr指向自己的实例并可以与已经存在的shared_ptr对象共享拥有权限的功能。
注意:只是简单返回共享指针 shared_ptr<T>(this)是有问题的,因为它会创建不同的ownership group。
Protected 成员函数:
Constructor---构造函数。
Destructor---析够函数
Operator= --- 赋值重载。
公共成员函数
shared_from_this--- 从*this获取 shared_ptr。
举例:
// enable_shared_from_this example #include <iostream> #include <memory>
struct C : std::enable_shared_from_this<C> { };
int main () { std::shared_ptr<C> foo, bar;
foo = std::make_shared<C>();
bar = foo->shared_from_this();
if (!foo.owner_before(bar) && !bar.owner_before(foo)) std::cout << "foo and bar share ownership";
return 0; }
|
输出:
foo and bar share ownership