• 智能指针shared_from_this


    shared_from_this()的用途

    资源对象的成员方法(不包括构造函数和析构函数)需要获取指向对象自身,即包含了this指针的shared_ptr

    使用原因

    1.把当前类对象作为参数传给其他函数时,为什么要传递share_ptr呢?直接传递this指针不可以吗?

    一个裸指针传递给调用者,谁也不知道调用者会干什么?假如调用者delete了该对象,而share_tr此时还指向该对象。

    2.这样传递share_ptr可以吗?share_ptr

    这样会造成2个非共享的share_ptr指向一个对象,最后造成2次析构该对象。

    使用示例

    #include
    #include
    using namespace std;
    class Base : public std::enable_shared_from_this<Base>
    {
    private:
        /* data */
    public:
        Base(/* args */){ cout << "constructor.."<< endl;}
        ~Base(){ cout << "delete.."<< endl; }
        std::shared_ptr<Base> getSharedFromThis(){return shared_from_this();}
        //注意获取共享指针的函数不能在析构函数或者析构的回调函数中调用
        void fun(){
            std::shared_ptr<Base> basePtr = enable_shared_from_this::shared_from_this();
            cout<< "use_count:"<< basePtr.use_count() <<endl;   //应用计数+2 说明获取共享指针成功
    
        }
    };
    
    class none_donging{
    public:
        void operator()(void* val){
            Base *base = (Base *)val;
            if (base)
            {
                delete base;
            }
        }
    };
    
    typedef std::shared_ptr<Base> BasePtr;
    
    int main(){
        {
            BasePtr basePtr = BasePtr(new Base,[=](void* val){
                //自定义析构
                Base* base = (Base*)val;
                if(base){
                    // base->fun(); //禁止在析构的回调函数中调用
                    delete base;
                }
            });
            basePtr->fun();
        }
        cout <<"==================="<<endl;
        {
            BasePtr basePtr = BasePtr(new Base,none_donging());
            BasePtr basePtr3 = basePtr->getSharedFromThis();
            cout<< "use_count:"<< basePtr3.use_count() <<endl;
        }
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    输出:

    constructor..
    use_count:2
    delete..
    ===================
    constructor..
    use_count:2
    delete..
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    linux minicom 调试串口
    视频监控系统/视频汇聚平台EasyCVR平台页面展示优化
    (附源码)springboot农田灌溉设备管理系统 毕业设计 260931
    javaScript 中的宏任务、微任务
    Flink Yarn Per Job - CliFrontend
    无风扇嵌入式车载电脑在矿山车辆行业应用
    HTML5 —— 初识 Canvas 画布
    java jdbc Incorrect string value for column
    webpack之Scope Hoisting(范围提升)
    zabbix自动发现和自动注册
  • 原文地址:https://blog.csdn.net/qq_44519484/article/details/126583412