C++11新特性之十:enable_shared_from_this

 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.  
  4. class Bad

  5. {

  6. public:

  7. std::shared_ptr<Bad> getptr() {

  8. return std::shared_ptr<Bad>(this);

  9. }

  10. ~Bad() { std::cout << "Bad::~Bad() called" << std::endl; }

  11. };

  12.  
  13. int main()

  14. {

  15. // 错误的示例,每个shared_ptr都认为自己是对象仅有的所有者

  16. std::shared_ptr<Bad> bp1(new Bad());

  17. std::shared_ptr<Bad> bp2 = bp1->getptr();

  18. // 打印bp1和bp2的引用计数

  19. std::cout << "bp1.use_count() = " << bp1.use_count() << std::endl;

  20. std::cout << "bp2.use_count() = " << bp2.use_count() << std::endl;

  21. } // Bad 对象将会被删除两次

输出结果如下:


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

正确的实现如下:

 
  1. #include <memory>

  2. #include <iostream>

  3.  
  4. struct Good : std::enable_shared_from_this<Good> // 注意:继承

  5. {

  6. public:

  7. std::shared_ptr<Good> getptr() {

  8. return shared_from_this();

  9. }

  10. ~Good() { std::cout << "Good::~Good() called" << std::endl; }

  11. };

  12.  
  13. int main()

  14. {

  15. // 大括号用于限制作用域,这样智能指针就能在system("pause")之前析构

  16. {

  17. std::shared_ptr<Good> gp1(new Good());

  18. std::shared_ptr<Good> gp2 = gp1->getptr();

  19. // 打印gp1和gp2的引用计数

  20. std::cout << "gp1.use_count() = " << gp1.use_count() << std::endl;

  21. std::cout << "gp2.use_count() = " << gp2.use_count() << std::endl;

  22. }

  23. system("pause");

  24. }

输出结果如下:

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

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

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

原文:https://blog.csdn.net/caoshangpa/article/details/79392878

猜你喜欢

转载自blog.csdn.net/yuhan61659/article/details/81585024