使用场景
当我们在对象函数中需要返回或者使用自己的 shared_ptr
指针时,该怎么办呢?常见的错误写法如下:用不安全的表达式试图获得 this
的 shared_ptr
对象, 但可能会导致 this
被多个互不知晓的所有者析构.
1 2 3 4 5 6 7
| struct Bad { std::shared_ptr<Bad> getptr() { return std::shared_ptr<Bad>(this); } ~Bad() { std::cout << "Bad::~Bad() called\n"; } };
|
1 2 3 4 5
| { std::shared_ptr<Bad> bp1 = std::make_shared<Bad>(); std::shared_ptr<Bad> bp2 = bp1->getptr(); std::cout << "bp2.use_count() = " << bp2.use_count() << '\n'; }
|
正确写法是将定义对象公开继承 enable_shared_from_this
:
1 2 3 4 5 6
| class Good: public std::enable_shared_from_this<Good> { std::shared_ptr<Good> getptr() { return shared_from_this(); } };
|