shord

xiaoxiao2021-02-28  201

#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 pointer size_type* pn; // reference counter public: //构造函数---------------------------------------------------2 explicit 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 throw return *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_ptr template<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

转载请注明原文地址: https://www.6miu.com/read-43217.html

最新回复(0)