智能指针手写
#include#define ll long longusing namespace std;templateclass 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& ptr):cnt(&(++*ptr.cnt)),_ptr(ptr._ptr){} T& operator*() { return *_ptr; } T* operator->() { return _ptr; } share_ptr& operator=(share_ptr& 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 pstr(new string("abc")); cout << "pstr:" << pstr.getRef() << " " << *pstr << endl; share_ptr pstr2(pstr); cout << "pstr:" << pstr.getRef() << " " << *pstr << endl; cout << "pstr2:" << pstr2.getRef() << " " << *pstr2 << endl; share_ptr 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;}
运行结果:
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~