namespace wang{ template<class T> class shared_ptr{ public: explicit shared_ptr(T *p) : count(new int(1)), Myptr_(p) {} shared_ptr(const shared_ptr<T>&other) { Myptr_ = other.Myptr_; count = &(++*other.count); } T* operator ->(){ return Myptr_; } T& operator *() { return *Myptr_; } shared_ptr<T>& operator=(shared_ptr<T> &other) { ++*other.count; if (this->ptr/*当前指针不为空*/ && 0 == --*this->count) { delete count; //这里不是很完善,数组的情况没考虑 delete Myptr_; } count = other.count; Myptr_ = other.Myptr_; return *this; } ~shared_ptr(){ if (0 == --*(this->count)) { delete count; delete Myptr_; } } int getRef(){ return *count; } private: T* Myptr_; int * count; }; }
代码不完善,大概是这个思路,赋值,拷贝构造,析构时都要考虑引用次数