• 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指向同一个对象,未增加引用计数导对象被析构两次。例如:

    #include <memory>
    #include <iostream>
     
    class Bad
    {
    public:
        std::shared_ptr<Bad> getptr() {
            return std::shared_ptr<Bad>(this);
        }
        ~Bad() { std::cout << "Bad::~Bad() called" << std::endl; }
    };
     
    int main()
    {
        // 错误的示例,每个shared_ptr都认为自己是对象仅有的所有者
        std::shared_ptr<Bad> bp1(new Bad());
        std::shared_ptr<Bad> bp2 = bp1->getptr();
        // 打印bp1和bp2的引用计数
        std::cout << "bp1.use_count() = " << bp1.use_count() << std::endl;
        std::cout << "bp2.use_count() = " << bp2.use_count() << std::endl;
    }  // Bad 对象将会被删除两次
    输出结果如下:

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


    正确的实现如下:

    #include <memory>
    #include <iostream>
     
    struct Good : std::enable_shared_from_this<Good> // 注意:继承
    {
    public:
        std::shared_ptr<Good> getptr() {
            return shared_from_this();
        }
        ~Good() { std::cout << "Good::~Good() called" << std::endl; }
    };
     
    int main()
    {
        // 大括号用于限制作用域,这样智能指针就能在system("pause")之前析构
        {
            std::shared_ptr<Good> gp1(new Good());
            std::shared_ptr<Good> gp2 = gp1->getptr();
            // 打印gp1和gp2的引用计数
            std::cout << "gp1.use_count() = " << gp1.use_count() << std::endl;
            std::cout << "gp2.use_count() = " << gp2.use_count() << std::endl;
        }
        system("pause");
    }
    输出结果如下:


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

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

    具体的应用可以参考:Boost.Asio C++ 网络编程之五:TCP回显服务端/客户端
    ————————————————
    版权声明:本文为CSDN博主「草上爬」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/caoshangpa/article/details/79392878

  • 相关阅读:
    第11组 Beta冲刺(1/5)
    第11组 Alpha事后诸葛亮
    第11组 Alpha冲刺(6/6)
    第11组 Alpha冲刺(5/6)
    第11组 Alpha冲刺(4/6)
    第11组 Alpha冲刺(3/6)
    毕设笔记
    软工实践个人总结
    第01组 Beta版本演示
    第01组 Beta冲刺(5/5)
  • 原文地址:https://www.cnblogs.com/cnhk19/p/15093450.html
Copyright © 2020-2023  润新知