C++实现简易共享指针
#include <iostream> #include <memory> using namespace std; template <typename T> class SharedPtr{ private: T *_ptr; int *_pcount; public: SharedPtr(T *ptr= nullptr):_ptr(ptr),_pcount(new int(1)){}//构造函数 SharedPtr(const SharedPtr &s):_ptr(s._ptr),_pcount(s._pcount){//用另一个共享指针初始化共享指针 (*_pcount)++; } SharedPtr<T> &operator=(const SharedPtr &s){//重载= if(this != &s) { if(--(*(this->_pcount))==0)// { delete this->_ptr; delete this->_pcount; } _ptr=s._ptr; _pcount=s._pcount; *(_pcount)++; } return *this; } T &operator*()//重载* { return *(this->_ptr); } T *operator->()//重载-> { return this->_ptr; } ~SharedPtr()//析构函数 { --(*(this->_pcount)); if(*(this->_pcount)==0) { delete _ptr; _ptr= nullptr; delete _pcount; _pcount= nullptr; } } }; int main() { std::shared_ptr<int> p1(new int(4)); cout<<"p1: "<<p1<<" *p1 "<<*p1; cout<<endl; return 0; }