shord_ptr
#include <iostream>
using namespace std;//shared_ptr的簡單實現版本
//基于引用記數的智能指針
//它可以和stl容器完美的配合template<class T>class shared_ptr{typedef T& reference;typedef T* pointer;typedef unsigned long size_type;private:T *px; // contained pointersize_type* pn; // reference counterpublic://構造函數---------------------------------------------------2explicit shared_ptr() : px(0), pn(){ }template<typename Y>shared_ptr(Y* py){pn = new size_type(1);px = py;}//copy構造函數------------------------------------------------shared_ptr(const shared_ptr& r) throw() : px(r.px){++*r.pn;pn = r.pn;}template<typename Y>shared_ptr(const shared_ptr<Y>& r)//用于多態{px = r.px;++*r.pn;pn = r.pn; //shared_count::op= doesn't throw}~shared_ptr() { dispose(); }//重載賦值operator=--------------------------------------------shared_ptr& operator=(const shared_ptr& r) throw(){if (this == &r) return *this;dispose();px = r.px;++*r.pn;pn = r.pn;return *this;}template<typename Y>shared_ptr& operator=(const shared_ptr<Y>& r)//用于多態{dispose();px = r.px;++*r.pn;pn = r.pn; //shared_count::op= doesn't throwreturn *this;} void reset(T* p = 0){if (px == p) return;if (--*pn == 0){delete(px);}else{try { pn = new size_type; }catch (...) {++*pn;delete(p);throw;} } *pn = 1;px = p;} reference operator*()const throw(){ return *px; }pointer operator->()const throw(){ return px; }pointer get() const throw(){ return px; }size_type use_count() const throw()//{return *pn;}bool unique() const throw()//{return *pn == 1;}private:void dispose() throw(){if (--*pn == 0){delete px; delete pn;}}}; // shared_ptrtemplate<typename A, typename B>inline bool operator==(shared_ptr<A>const & l, shared_ptr<B> const & r){return l.get() == r.get();}template<typename A, typename B>inline bool operator!=(shared_ptr<A>const & l, shared_ptr<B> const & r){return l.get() != r.get();}int main()
{ shared_ptr<int> sp( new int(2) );shared_ptr<int> sp2( sp );cout << *sp << ends << *sp2 << endl;cout << sp.use_count() << ends << sp2.use_count() << endl;return 0;
}
輸出:
2 2
2 2
總結
- 上一篇: 【最新】2021自动化测试面试宝典100
- 下一篇: 计算机术语位字节字字长分别是什么,字长、