C++11新特性——enable_shared_from_this

      版权声明:本文为灿哥哥http://blog.csdn.net/caoshangpa原创文章,转载请标明出处。           https://blog.csdn.net/caoshangpa/article/details/79392878        </div>
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
                          <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
      <div class="htmledit_views" id="content_views">

       enable_shared_from_this是一个模板类,定义于头文件<memory>,其原型为:

template< class T > class enable_shared_from_this;
       std::enable_shared_from_this 能让一个对象(假设其名为 t ,且已被一个 std::shared_ptr 对象 pt 管理)安全地生成其他额外的 std::shared_ptr 实例(假设名为 pt1, pt2, ... ) ,它们与 pt 共享对象 t 的所有权。
       若一个类 T 继承 std::enable_shared_from_this<T> ,则会为该类 T 提供成员函数: shared_from_this 。 当 T 类型对象 t 被一个为名为 pt 的 std::shared_ptr<T> 类对象管理时,调用 T::shared_from_this 成员函数,将会返回一个新的 std::shared_ptr<T> 对象,它与 pt 共享 t 的所有权。

一.使用场合

       当类A被share_ptr管理,且在类A的成员函数里需要把当前类对象作为参数传给其他函数时,就需要传递一个指向自身的share_ptr。

1.为何不直接传递this指针

       使用智能指针的初衷就是为了方便资源管理,如果在某些地方使用智能指针,某些地方使用原始指针,很容易破坏智能指针的语义,从而产生各种错误。

2.可以直接传递share_ptr<this>么?

       答案是不能,因为这样会造成2个非共享的share_ptr指向同一个对象,未增加引用计数导对象被析构两次。例如:

  1. #include <memory>
  2. #include <iostream>
  3. class Bad
  4. {
  5. public:
  6. std::shared_ptr<Bad> getptr() {
  7. return std::shared_ptr<Bad>(this);
  8. }
  9. ~Bad() { std::cout << "Bad::~Bad() called" << std::endl; }
  10. };
  11. int main()
  12. {
  13. // 错误的示例,每个shared_ptr都认为自己是对象仅有的所有者
  14. std::shared_ptr<Bad> bp1(new Bad());
  15. std::shared_ptr<Bad> bp2 = bp1->getptr();
  16. // 打印bp1和bp2的引用计数
  17. std::cout << "bp1.use_count() = " << bp1.use_count() << std::endl;
  18. std::cout << "bp2.use_count() = " << bp2.use_count() << std::endl;
  19. } // Bad 对象将会被删除两次
输出结果如下:


当然,一个对象被删除两次会导致崩溃。


正确的实现如下:

  1. #include <memory>
  2. #include <iostream>
  3. struct Good : std::enable_shared_from_this<Good> // 注意:继承
  4. {
  5. public:
  6. std::shared_ptr<Good> getptr() {
  7. return shared_from_this();
  8. }
  9. ~Good() { std::cout << "Good::~Good() called" << std::endl; }
  10. };
  11. int main()
  12. {
  13. // 大括号用于限制作用域,这样智能指针就能在system("pause")之前析构
  14. {
  15. std::shared_ptr<Good> gp1(new Good());
  16. std::shared_ptr<Good> gp2 = gp1->getptr();
  17. // 打印gp1和gp2的引用计数
  18. std::cout << "gp1.use_count() = " << gp1.use_count() << std::endl;
  19. std::cout << "gp2.use_count() = " << gp2.use_count() << std::endl;
  20. }
  21. system("pause");
  22. }
输出结果如下:

二.为何会出现这种使用场合

       因为在异步调用中,存在一个保活机制,异步函数执行的时间点我们是无法确定的,然而异步函数可能会使用到异步调用之前就存在的变量。为了保证该变量在异步函数执期间一直有效,我们可以传递一个指向自身的share_ptr给异步函数,这样在异步函数执行期间share_ptr所管理的对象就不会析构,所使用的变量也会一直有效了(保活)。

具体的应用可以参考:Boost.Asio C++ 网络编程之五:TCP回显服务端/客户端

posted @ 2019-05-19 21:43  unique_ptr  阅读(677)  评论(0编辑  收藏  举报