首页 / 操作系统 / Linux / C++智能指针 shared_ptr
shared_ptr 是一个标准的共享所有权的智能指针, 允许多个指针指向同一个对象. 定义在 memory 文件中(非memory.h), 命名空间为 std. shared_ptr 是为了解决 auto_ptr 在对象所有权上的局限性(auto_ptr 是独占的), 在使用引用计数的机制上提供了可以共享所有权的智能指针, 当然这需要额外的开销:
(1) shared_ptr 对象除了包括一个所拥有对象的指针外, 还必须包括一个引用计数代理对象的指针.
(2) 时间上的开销主要在初始化和拷贝操作上, *和->操作符重载的开销跟auto_ptr是一样.
(3) 开销并不是我们不使用shared_ptr的理由, 永远不要进行不成熟的优化, 直到性能分析器告诉你这一点. 使用方法:可以使用模板函数 make_shared 创建对象, make_shared 需指定类型("<>"中)及参数("()"内), 传递的参数必须与指定的类型的构造函数匹配. 如:
std::shared_ptr<int> sp1 = std::make_shared<int>(10);
std::shared_ptr<std::string> sp2 = std::make_shared<std::string>("Hello c++");
也可以定义 auto 类型的变量来保存 make_shared 的结果.
auto sp3 = std::make_shared<int>(11);
printf("sp3=%d
", *sp3);
auto sp4 = std::make_shared<std::string>("C++11");
printf("sp4=%s
", (*sp4).c_str());
成员函数
use_count 返回引用计数的个数
unique 返回是否是独占所有权( use_count 为 1)
swap 交换两个 shared_ptr 对象(即交换所拥有的对象)
reset 放弃内部对象的所有权或拥有对象的变更, 会引起原有对象的引用计数的减少
get 返回内部对象(指针), 由于已经重载了()方法, 因此和直接使用对象是一样的.如 shared_ptr<int> sp(new int(1)); sp 与 sp.get()是等价的以下代码演示各个函数的用法与特点:std::shared_ptr<int> sp0(new int(2));std::shared_ptr<int> sp1(new int(11));std::shared_ptr<int> sp2 = sp1;printf("%d
", *sp0); // 2printf("%d
", *sp1); // 11printf("%d
", *sp2); // 11sp1.swap(sp0);printf("%d
", *sp0); // 11printf("%d
", *sp1); // 2printf("%d
", *sp2); // 11std::shared_ptr<int> sp3(new int(22));std::shared_ptr<int> sp4 = sp3;printf("%d
", *sp3); // 22printf("%d
", *sp4); // 22sp3.reset();printf("%d
", sp3.use_count());// 0printf("%d
", sp4.use_count());// 1printf("%d
", sp3);// 0printf("%d
", sp4);// 指向所拥有对象的地址std::shared_ptr<int> sp5(new int(22));std::shared_ptr<int> sp6 = sp5;std::shared_ptr<int> sp7 = sp5;printf("%d
", *sp5); // 22printf("%d
", *sp6); // 22printf("%d
", *sp7); // 22printf("%d
", sp5.use_count());// 3printf("%d
", sp6.use_count());// 3printf("%d
", sp7.use_count());// 3sp5.reset(new int(33));printf("%d
", sp5.use_count());// 1printf("%d
", sp6.use_count());// 2printf("%d
", sp7.use_count());// 2printf("%d
", *sp5); // 33printf("%d
", *sp6); // 22printf("%d
", *sp7); // 22shared_ptr 的赋值构造函数和拷贝构造函数:
auto r = std::make_shared<int>(); // r 的指向的对象只有一个引用, 其 use_count == 1
auto q = r; (或auto q(r);) // 给 r 赋值, 令其指向另一个地址, q 原来指向的对象的引用计数减1(如果为0, 释放内存), r指向的对象的引用计数加1, 此时 q 与 r 指向同一个对象, 并且其引用计数相同, 都为原来的值加1.
以下面的代码测试:std::shared_ptr<int> sp1 = std::make_shared<int>(10);std::shared_ptr<int> sp2 = std::make_shared<int>(11);auto sp3 = sp2; 或 auto sp3(sp2);printf("sp1.use_count = %d
", sp1.use_count());// 1printf("sp2.use_count = %d
", sp2.use_count());// 2printf("sp3.use_count = %d
", sp3.use_count());// 2sp3 = sp1;printf("sp1.use_count = %d
", sp1.use_count());// 2printf("sp2.use_count = %d
", sp2.use_count());// 1printf("sp3.use_count = %d
", sp3.use_count());// 2 何时需要使用 shared_ptr ?
(1) 程序不知道自己需要使用多少对象. 如使用窗口类, 使用 shared_ptr 为了让多个对象能共享相同的底层数据.std::vector<std::string> v1; // 一个空的 vector// 在某个新的作用域中拷贝数据到 v1 中{std::vector<std::string> v2;v2.push_back("a");v2.push_back("b");v2.push_back("c");v1 = v2;} // 作用域结束时 v2 被销毁, 数据被拷贝到 v1 中(2) 程序不知道所需对象的准确类型.
(3) 程序需要在多个对象间共享数据.自定义释放器(函数)
自定义释放器(函数), 它能完成对 shared_ptr 中保存的指针进行释放操作, 还能处理 shared_ptr 的内部对象未完成的部分工作. 假设如下是一个连接管理类, 此类由于历史原因, 无法在析构函数中进行断开连接, 此时用自定义的释放器可以很好的完成此工作:class CConnnect{void Disconnect() { PRINT_FUN(); }};void Deleter(CConnnect* obj){obj->Disconnect(); // 做其它释放或断开连接等工作delete obj; // 删除对象指针}std::shared_ptr<CConnnect> sps(new CConnnect, Deleter);使用 shared_ptr 的注意事项
(1) shared_ptr 作为被保护的对象的成员时, 小心因循环引用造成无法释放资源.
假设 a 对象中含有一个 shared_ptr<CB> 指向 b 对象, b 对象中含有一个 shared_ptr<CA> 指向 a 对象, 并且 a, b 对象都是堆中分配的。
考虑对象 b 中的 m_spa 是我们能最后一个看到 a 对象的共享智能指针, 其 use_count 为2, 因为对象 b 中持有 a 的指针, 所以当 m_spa 说再见时, m_spa 只是把 a 对象的 use_count 改成1; 对象 a 同理; 然后就失去了 a,b 对象的联系.
解决此方法是使用 weak_ptr 替换 shared_ptr . 以下为错误用法, 导致相互引用, 最后无法释放对象class CB;class CA;class CA{public:CA(){}~CA(){PRINT_FUN();}void Register(const std::shared_ptr<CB>& sp){m_sp = sp;}private:std::shared_ptr<CB> m_sp;};class CB{public:CB(){};~CB(){PRINT_FUN();};void Register(const std::shared_ptr<CA>& sp){m_sp = sp;}private:std::shared_ptr<CA> m_sp;};std::shared_ptr<CA> spa(new CA);std::shared_ptr<CB> spb(new CB);spb->Register(spa);spa->Register(spb);printf("%d
", spb.use_count()); // 2printf("%d
", spa.use_count()); // 2 运行上述代码会发现 CA, CB 析构函数都不会打印. 因为他们都没有释放内存. (2) 小心对象内部生成 shared_ptrclass Y : public std::enable_shared_from_this<Y>{public:std::shared_ptr<Y> GetSharePtr(){return shared_from_this();}}; 对普通的类(没有继承 enable_shared_from_this) T 的 shared_ptr<T> p(new T). p 作为栈对象占8个字节,为了记录( new T )对象的引用计数, p 会在堆上分配 16 个字节以保存引用计数等“智能信息”.
share_ptr 没有“嵌入(intrusive)”到T对象, 或者说T对象对 share_ptr 毫不知情.
而 Y 对象则不同, Y 对象已经被“嵌入”了一些 share_ptr 相关的信息, 目的是为了找到“全局性”的那16字节的本对象的“智能信息”.考虑下面的代码:Y y;std::shared_ptr<Y> spy = y.GetSharePtr(); // 错误, y 根本不是 new 创建的Y* y = new Y;std::shared_ptr<Y> spy = y->GetSharePtr(); // 错误, 问题依旧存在, 程序直接崩溃正确用法:std::shared_ptr<Y> spy(new Y);std::shared_ptr<Y> p = spy->GetSharePtr();printf("%d
", p.use_count()); // 2 (3) 小心多线程对引用计数的影响首先, 如果是轻量级的锁, 比如 InterLockIncrement 等, 对程序影响不大; 如果是重量级的锁, 就要考虑因为 share_ptr 维护引用计数而造成的上下文切换开销.
其次, 多线程同时对 shared_ptr 读写时, 行为不确定, 因为shared_ptr本身有两个成员px,pi. 多线程同时对 px 读写要出问题, 与一个 int 的全局变量多线程读写会出问题的原因一样.(4) 与 weak_ptr 一起工作时, weak_ptr 在使用前需要检查合法性std::weak_ptr<A> wp;{std::shared_ptr<A>sp(new A);//sp.use_count()==1wp = sp; //wp不会改变引用计数,所以sp.use_count()==1std::shared_ptr<A> sp2 = wp.lock(); //wp没有重载->操作符。只能这样取所指向的对象}printf("expired:%d
", wp.expired()); // 1std::shared_ptr<A> sp_null = wp.lock(); //sp_null .use_count()==0;上述代码中 sp 和 sp2 离开了作用域, 其容纳的对象已经被释放了. 得到了一个容纳 NULL 指针的 sp_null 对象.
在使用 wp 前需要调用 wp.expired() 函数判断一下. 因为 wp 还仍旧存在, 虽然引用计数等于0,仍有某处“全局”性的存储块保存着这个计数信息.
直到最后一个 weak_ptr 对象被析构, 这块“堆”存储块才能被回收, 否则 weak_ptr 无法知道自己所容纳的那个指针资源的当前状态. (5) shared_ptr 不支持数组, 如果使用数组, 需要自定义删除器, 如下是一个利用 lambda 实现的删除器: std::shared_ptr<int> sps(new int[10], [](int *p){delete[] p;}); 对于数组元素的访问, 需使要使用 get 方法取得内部元素的地址后, 再加上偏移量取得.for (size_t i = 0; i < 10; i++){*((int*)sps.get() + i) = 10 - i;}for (size_t i = 0; i < 10; i++){printf("%d -- %d
", i, *((int*)sps.get() + i));} VC中的源码实现template<class _Ty>class _Ptr_base{// base class for shared_ptr and weak_ptrpublic:typedef _Ptr_base<_Ty> _Myt;typedef _Ty _Elem;typedef _Elem element_type;_Ptr_base(): _Ptr(0), _Rep(0){// construct}_Ptr_base(_Myt&& _Right): _Ptr(0), _Rep(0){// construct _Ptr_base object that takes resource from _Right_Assign_rv(_STD forward<_Myt>(_Right));}template<class _Ty2>_Ptr_base(_Ptr_base<_Ty2>&& _Right): _Ptr(_Right._Ptr), _Rep(_Right._Rep){// construct _Ptr_base object that takes resource from _Right_Right._Ptr = 0;_Right._Rep = 0;}_Myt& operator=(_Myt&& _Right){// construct _Ptr_base object that takes resource from _Right_Assign_rv(_STD forward<_Myt>(_Right));return (*this);}void _Assign_rv(_Myt&& _Right){// assign by moving _Rightif (this != &_Right)_Swap(_Right);}long use_count() const{// return use countreturn (_Rep ? _Rep->_Use_count() : 0);}void _Swap(_Ptr_base& _Right){// swap pointers_STD swap(_Rep, _Right._Rep);_STD swap(_Ptr, _Right._Ptr);}template<class _Ty2>bool owner_before(const _Ptr_base<_Ty2>& _Right) const{// compare addresses of manager objectsreturn (_Rep < _Right._Rep);}void *_Get_deleter(const _XSTD2 type_info& _Type) const{// return pointer to deleter object if its type is _Typereturn (_Rep ? _Rep->_Get_deleter(_Type) : 0);}_Ty *_Get() const{// return pointer to resourcereturn (_Ptr);}bool _Expired() const{// test if expiredreturn (!_Rep || _Rep->_Expired());}void _Decref(){// decrement reference countif (_Rep != 0)_Rep->_Decref();}void _Reset(){// release resource_Reset(0, 0);}template<class _Ty2>void _Reset(const _Ptr_base<_Ty2>& _Other){// release resource and take ownership of _Other._Ptr_Reset(_Other._Ptr, _Other._Rep, false);}template<class _Ty2>void _Reset(const _Ptr_base<_Ty2>& _Other, bool _Throw){// release resource and take ownership from weak_ptr _Other._Ptr_Reset(_Other._Ptr, _Other._Rep, _Throw);}template<class _Ty2>void _Reset(const _Ptr_base<_Ty2>& _Other, const _Static_tag&){// release resource and take ownership of _Other._Ptr_Reset(static_cast<_Elem *>(_Other._Ptr), _Other._Rep);}template<class _Ty2>void _Reset(const _Ptr_base<_Ty2>& _Other, const _Const_tag&){// release resource and take ownership of _Other._Ptr_Reset(const_cast<_Elem *>(_Other._Ptr), _Other._Rep);}template<class _Ty2>void _Reset(const _Ptr_base<_Ty2>& _Other, const _Dynamic_tag&){// release resource and take ownership of _Other._Ptr_Elem *_Ptr = dynamic_cast<_Elem *>(_Other._Ptr);if (_Ptr)_Reset(_Ptr, _Other._Rep);else_Reset();}template<class _Ty2>void _Reset(auto_ptr<_Ty2>& _Other){// release resource and take _Other.get()_Ty2 *_Px = _Other.get();_Reset0(_Px, new _Ref_count<_Elem>(_Px));_Other.release();_Enable_shared(_Px, _Rep);}#if _HAS_CPP0Xtemplate<class _Ty2>void _Reset(_Ty *_Ptr, const _Ptr_base<_Ty2>& _Other){// release resource and alias _Ptr with _Other_rep_Reset(_Ptr, _Other._Rep);}#endif /* _HAS_CPP0X */void _Reset(_Ty *_Other_ptr, _Ref_count_base *_Other_rep){// release resource and take _Other_ptr through _Other_repif (_Other_rep)_Other_rep->_Incref();_Reset0(_Other_ptr, _Other_rep);}void _Reset(_Ty *_Other_ptr, _Ref_count_base *_Other_rep, bool _Throw){// take _Other_ptr through _Other_rep from weak_ptr if not expired// otherwise, leave in default state if !_Throw,// otherwise throw exceptionif (_Other_rep && _Other_rep->_Incref_nz())_Reset0(_Other_ptr, _Other_rep);else if (_Throw)_THROW_NCEE(bad_weak_ptr, 0);}void _Reset0(_Ty *_Other_ptr, _Ref_count_base *_Other_rep){// release resource and take new resourceif (_Rep != 0)_Rep->_Decref();_Rep = _Other_rep;_Ptr = _Other_ptr;}void _Decwref(){// decrement weak reference countif (_Rep != 0)_Rep->_Decwref();}void _Resetw(){// release weak reference to resource_Resetw((_Elem *)0, 0);}template<class _Ty2>void _Resetw(const _Ptr_base<_Ty2>& _Other){// release weak reference to resource and take _Other._Ptr_Resetw(_Other._Ptr, _Other._Rep);}template<class _Ty2>void _Resetw(const _Ty2 *_Other_ptr, _Ref_count_base *_Other_rep){// point to _Other_ptr through _Other_rep_Resetw(const_cast<_Ty2*>(_Other_ptr), _Other_rep);}template<class _Ty2>void _Resetw(_Ty2 *_Other_ptr, _Ref_count_base *_Other_rep){// point to _Other_ptr through _Other_repif (_Other_rep)_Other_rep->_Incwref();if (_Rep != 0)_Rep->_Decwref();_Rep = _Other_rep;_Ptr = _Other_ptr;}private:_Ty *_Ptr;_Ref_count_base *_Rep;template<class _Ty0>friend class _Ptr_base;};template<class _Ty>class shared_ptr: public _Ptr_base<_Ty>{// class for reference counted resource managementpublic:typedef shared_ptr<_Ty> _Myt;typedef _Ptr_base<_Ty> _Mybase;shared_ptr(){// construct empty shared_ptr object}template<class _Ux>explicit shared_ptr(_Ux *_Px){// construct shared_ptr object that owns _Px_Resetp(_Px);}template<class _Ux,class _Dx>shared_ptr(_Ux *_Px, _Dx _Dt){// construct with _Px, deleter_Resetp(_Px, _Dt);}//#if _HAS_CPP0X#if defined(_NATIVE_NULLPTR_SUPPORTED) && !defined(_DO_NOT_USE_NULLPTR_IN_STL)shared_ptr(_STD nullptr_t){// construct with nullptr_Resetp((_Ty *)0);}template<class _Dx>shared_ptr(_STD nullptr_t, _Dx _Dt){// construct with nullptr, deleter_Resetp((_Ty *)0, _Dt);}template<class _Dx,class _Alloc>shared_ptr(_STD nullptr_t, _Dx _Dt, _Alloc _Ax){// construct with nullptr, deleter, allocator_Resetp((_Ty *)0, _Dt, _Ax);}#endif /* defined(_NATIVE_NULLPTR_SUPPORTED) etc. */template<class _Ux,class _Dx,class _Alloc>shared_ptr(_Ux *_Px, _Dx _Dt, _Alloc _Ax){// construct with _Px, deleter, allocator_Resetp(_Px, _Dt, _Ax);}//#endif /* _HAS_CPP0X */#if _HAS_CPP0Xtemplate<class _Ty2>shared_ptr(const shared_ptr<_Ty2>& _Right, _Ty *_Px){// construct shared_ptr object that aliases _Rightthis->_Reset(_Px, _Right);}#endif /* _HAS_CPP0X */shared_ptr(const _Myt& _Other){// construct shared_ptr object that owns same resource as _Otherthis->_Reset(_Other);}template<class _Ty2>shared_ptr(const shared_ptr<_Ty2>& _Other,typename enable_if<is_convertible<_Ty2 *, _Ty *>::value,void *>::type * = 0){// construct shared_ptr object that owns same resource as _Otherthis->_Reset(_Other);}template<class _Ty2>explicit shared_ptr(const weak_ptr<_Ty2>& _Other,bool _Throw = true){// construct shared_ptr object that owns resource *_Otherthis->_Reset(_Other, _Throw);}template<class _Ty2>shared_ptr(auto_ptr<_Ty2>& _Other){// construct shared_ptr object that owns *_Other.get()this->_Reset(_Other);}template<class _Ty2>shared_ptr(const shared_ptr<_Ty2>& _Other, const _Static_tag& _Tag){// construct shared_ptr object for static_pointer_castthis->_Reset(_Other, _Tag);}template<class _Ty2>shared_ptr(const shared_ptr<_Ty2>& _Other, const _Const_tag& _Tag){// construct shared_ptr object for const_pointer_castthis->_Reset(_Other, _Tag);}template<class _Ty2>shared_ptr(const shared_ptr<_Ty2>& _Other, const _Dynamic_tag& _Tag){// construct shared_ptr object for dynamic_pointer_castthis->_Reset(_Other, _Tag);}shared_ptr(_Myt&& _Right): _Mybase(_STD forward<_Myt>(_Right)){// construct shared_ptr object that takes resource from _Right}template<class _Ty2>shared_ptr(shared_ptr<_Ty2>&& _Right,typename enable_if<is_convertible<_Ty2 *, _Ty *>::value,void *>::type * = 0): _Mybase(_STD forward<shared_ptr<_Ty2> >(_Right)){// construct shared_ptr object that takes resource from _Right}#if _HAS_CPP0Xtemplate<class _Ux,class _Dx>shared_ptr(_STD unique_ptr<_Ux, _Dx>&& _Right){// construct from unique_ptr_Resetp(_Right.release(), _Right.get_deleter());}template<class _Ux,class _Dx>_Myt& operator=(unique_ptr<_Ux, _Dx>&& _Right){// move from unique_ptrshared_ptr(_STD move(_Right)).swap(*this);return (*this);}#endif /* _HAS_CPP0X */_Myt& operator=(_Myt&& _Right){// construct shared_ptr object that takes resource from _Rightshared_ptr(_STD move(_Right)).swap(*this);return (*this);}template<class _Ty2>_Myt& operator=(shared_ptr<_Ty2>&& _Right){// construct shared_ptr object that takes resource from _Rightshared_ptr(_STD move(_Right)).swap(*this);return (*this);}void swap(_Myt&& _Right){// exchange contents with movable _Right_Mybase::swap(_STD move(_Right));}~shared_ptr(){// release resourcethis->_Decref();}_Myt& operator=(const _Myt& _Right){// assign shared ownership of resource owned by _Rightshared_ptr(_Right).swap(*this);return (*this);}template<class _Ty2>_Myt& operator=(const shared_ptr<_Ty2>& _Right){// assign shared ownership of resource owned by _Rightshared_ptr(_Right).swap(*this);return (*this);}template<class _Ty2>_Myt& operator=(auto_ptr<_Ty2>& _Right){// assign ownership of resource pointed to by _Rightshared_ptr(_Right).swap(*this);return (*this);}void reset(){// release resource and convert to empty shared_ptr objectshared_ptr().swap(*this);}template<class _Ux>void reset(_Ux *_Px){// release, take ownership of _Pxshared_ptr(_Px).swap(*this);}template<class _Ux,class _Dx>void reset(_Ux *_Px, _Dx _Dt){// release, take ownership of _Px, with deleter _Dtshared_ptr(_Px, _Dt).swap(*this);}//#if _HAS_CPP0Xtemplate<class _Ux,class _Dx,class _Alloc>void reset(_Ux *_Px, _Dx _Dt, _Alloc _Ax){// release, take ownership of _Px, with deleter _Dt, allocator _Axshared_ptr(_Px, _Dt, _Ax).swap(*this);}//#endif /* _HAS_CPP0X */void swap(_Myt& _Other){// swap pointersthis->_Swap(_Other);}_Ty *get() const{// return pointer to resourcereturn (this->_Get());}typename tr1::add_reference<_Ty>::type operator*() const{// return reference to resourcereturn (*this->_Get());}_Ty *operator->() const{// return pointer to resourcereturn (this->_Get());}bool unique() const{// return true if no other shared_ptr object owns this resourcereturn (this->use_count() == 1);}_OPERATOR_BOOL() const{// test if shared_ptr object owns no resourcereturn (this->_Get() != 0 ? _CONVERTIBLE_TO_TRUE : 0);}private:template<class _Ux>void _Resetp(_Ux *_Px){// release, take ownership of _Px_TRY_BEGIN// allocate control block and reset_Resetp0(_Px, new _Ref_count<_Ux>(_Px));_CATCH_ALL// allocation failed, delete resourcedelete _Px;_RERAISE;_CATCH_END}template<class _Ux,class _Dx>void _Resetp(_Ux *_Px, _Dx _Dt){// release, take ownership of _Px, deleter _Dt_TRY_BEGIN// allocate control block and reset_Resetp0(_Px, new _Ref_count_del<_Ux, _Dx>(_Px, _Dt));_CATCH_ALL// allocation failed, delete resource_Dt(_Px);_RERAISE;_CATCH_END}//#if _HAS_CPP0Xtemplate<class _Ux,class _Dx,class _Alloc>void _Resetp(_Ux *_Px, _Dx _Dt, _Alloc _Ax){// release, take ownership of _Px, deleter _Dt, allocator _Axtypedef _Ref_count_del_alloc<_Ux, _Dx, _Alloc> _Refd;typename _Alloc::template rebind<_Refd>::other _Al = _Ax;_TRY_BEGIN// allocate control block and reset_Refd *_Ptr = _Al.allocate(1);new (_Ptr) _Refd(_Px, _Dt, _Al);_Resetp0(_Px, _Ptr);_CATCH_ALL// allocation failed, delete resource_Dt(_Px);_RERAISE;_CATCH_END}//#endif /* _HAS_CPP0X */public:template<class _Ux>void _Resetp0(_Ux *_Px, _Ref_count_base *_Rx){// release resource and take ownership of _Pxthis->_Reset0(_Px, _Rx);_Enable_shared(_Px, _Rx);}};本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-12/137998.htm