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: 不可修改內(nèi)容的共享指針
// PtrConst: 不可修改指針的共享指針,內(nèi)容可以修改
// 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);
}
外部調(diào)用方法;
testA::Ptr 表示智能指針 |