打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
enable_shared_from_this 实现
template<class T>

class enable_shared_from_this

{

protected:

enable_shared_from_this()

{}



enable_shared_from_this(enable_shared_from_this const &)

{}



enable_shared_from_this & operator=(enable_shared_from_this const &)

{

return *this;

}



~enable_shared_from_this()

{}



public:

shared_ptr<T> shared_from_this()

{

return weak_this_.lock();

}



weak_ptr<T> weak_from_this()

{

return weak_this_;

}



private:

mutable weak_ptr<T> weak_this_;

};

项目中使用:

class A : public enable_shared_from_this<A>

{

public:

    A():mptr(new int

    {

        cout << "A()" << endl;

    }

    ~A()

    {

        cout << "~A()" << endl;

        delete mptr

        mptr = nullptr;

    }

    shared_ptr<AgetSharedPtr() 

    { 

        return shared_from_this(); 

    }

private:

    int *mptr;

};

// Ptr: 普通共享指针// ConstPtr: 不可修改内容的共享指针// PtrConst: 不可修改指针的共享指针,内容可以修改// ConstPtrConst: 只能初始化的指针,不能做任何的修改动作#define SHARED_PTR_DEFINE(X) public: typedef std::shared_ptrPtr; typedef std::shared_ptrConstPtr; typedef const std::shared_ptrPtrConst; typedef const std::shared_ptrConstPtrConst; class testA : public std::enable_shared_from_this{ SHARED_PTR_DEFINE(testA);}外部调用方法;testA::Ptr 表示智能指针

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用enable_shared_from_this
shared_from_this 几个值得注意的地方
伯乐在线博客
Boost智能指针
c 智能指针的使用
【转】C++ 智能指针详解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服