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<A> getSharedPtr() { 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 表示智能指针 |
赞 (0)