智能指针手写
#include<bits/stdc++.h> #define ll long long using namespace std; template<typename T> class share_ptr{ private: T* _ptr; int* cnt; public: share_ptr():cnt(new int(1)),_ptr(new T){} share_ptr(T* p) : cnt(new int(1)), _ptr(p) {} share_ptr(share_ptr<T>& ptr):cnt(&(++*ptr.cnt)),_ptr(ptr._ptr){} T& operator*() { return *_ptr; } T* operator->() { return _ptr; } share_ptr<T>& operator=(share_ptr<T>& other) { if(this==&other) { return *this; } ++*other.cnt; if(cnt!=nullptr&&--*cnt==0) { delete _ptr; delete cnt; } _ptr=other._ptr; cnt=other.cnt; return *this; } ~share_ptr(){ if(cnt!=nullptr&&--*cnt==0) { delete cnt; delete _ptr; } } int getRef(){ return *cnt; } }; int main() { share_ptr<string> pstr(new string("abc")); cout << "pstr:" << pstr.getRef() << " " << *pstr << endl; share_ptr<string> pstr2(pstr); cout << "pstr:" << pstr.getRef() << " " << *pstr << endl; cout << "pstr2:" << pstr2.getRef() << " " << *pstr2 << endl; share_ptr<string> pstr3(new string("hao")); cout << "pstr3:" << pstr3.getRef() << " " << *pstr3 << endl; pstr3 = pstr2; cout << "pstr:" << pstr.getRef() << " " << *pstr << endl; cout << "pstr2:" << pstr2.getRef() << " " << *pstr2 << endl; cout << "pstr3:" << pstr3.getRef() << " " << *pstr3 << endl; return 0; }
运行结果: