智能指针shared_from_this

shared_from_this()的用途

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

使用原因

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

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

2.这样传递share_ptr可以吗?share_ptr <this>

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

使用示例

#include<iostream>
#include<memory>
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;
}

输出:

constructor..
use_count:2
delete..
===================
constructor..
use_count:2
delete..
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DeRoy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值