shared_ptr.h

Go to the documentation of this file.
00001 // shared_ptr and weak_ptr implementation -*- C++ -*-
00002 
00003 // Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
00004 //
00005 // This file is part of the GNU ISO C++ Library.  This library is free
00006 // software; you can redistribute it and/or modify it under the
00007 // terms of the GNU General Public License as published by the
00008 // Free Software Foundation; either version 3, or (at your option)
00009 // any later version.
00010 
00011 // This library is distributed in the hope that it will be useful,
00012 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014 // GNU General Public License for more details.
00015 
00016 // Under Section 7 of GPL version 3, you are granted additional
00017 // permissions described in the GCC Runtime Library Exception, version
00018 // 3.1, as published by the Free Software Foundation.
00019 
00020 // You should have received a copy of the GNU General Public License and
00021 // a copy of the GCC Runtime Library Exception along with this program;
00022 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
00023 // <http://www.gnu.org/licenses/>.
00024 
00025 // GCC Note: Based on files from version 1.32.0 of the Boost library.
00026 
00027 //  shared_count.hpp
00028 //  Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd.
00029 
00030 //  shared_ptr.hpp
00031 //  Copyright (C) 1998, 1999 Greg Colvin and Beman Dawes.
00032 //  Copyright (C) 2001, 2002, 2003 Peter Dimov
00033 
00034 //  weak_ptr.hpp
00035 //  Copyright (C) 2001, 2002, 2003 Peter Dimov
00036 
00037 //  enable_shared_from_this.hpp
00038 //  Copyright (C) 2002 Peter Dimov
00039 
00040 // Distributed under the Boost Software License, Version 1.0. (See
00041 // accompanying file LICENSE_1_0.txt or copy at
00042 // http://www.boost.org/LICENSE_1_0.txt)
00043 
00044 /** @file bits/shared_ptr.h
00045  *  This is an internal header file, included by other library headers.
00046  *  You should not attempt to use it directly.
00047  */
00048 
00049 #ifndef _SHARED_PTR_H
00050 #define _SHARED_PTR_H 1
00051 
00052 #include <bits/shared_ptr_base.h>
00053 
00054 _GLIBCXX_BEGIN_NAMESPACE(std)
00055 
00056   /**
00057    * @addtogroup pointer_abstractions
00058    * @{
00059    */
00060 
00061   /// 2.2.3.7 shared_ptr I/O
00062   template<typename _Ch, typename _Tr, typename _Tp, _Lock_policy _Lp>
00063     inline std::basic_ostream<_Ch, _Tr>&
00064     operator<<(std::basic_ostream<_Ch, _Tr>& __os,
00065            const __shared_ptr<_Tp, _Lp>& __p)
00066     {
00067       __os << __p.get();
00068       return __os;
00069     }
00070 
00071   /// 2.2.3.10 shared_ptr get_deleter (experimental)
00072   template<typename _Del, typename _Tp, _Lock_policy _Lp>
00073     inline _Del*
00074     get_deleter(const __shared_ptr<_Tp, _Lp>& __p)
00075     {
00076 #ifdef __GXX_RTTI
00077       return static_cast<_Del*>(__p._M_get_deleter(typeid(_Del)));
00078 #else
00079       return 0;
00080 #endif
00081     }
00082 
00083 
00084   /**
00085    *  @brief  A smart pointer with reference-counted copy semantics.
00086    *
00087    *  The object pointed to is deleted when the last shared_ptr pointing to
00088    *  it is destroyed or reset.
00089   */
00090   template<typename _Tp>
00091     class shared_ptr : public __shared_ptr<_Tp>
00092     {
00093     public:
00094       /**
00095        *  @brief  Construct an empty %shared_ptr.
00096        *  @post   use_count()==0 && get()==0
00097        */
00098       shared_ptr() : __shared_ptr<_Tp>() { }
00099 
00100       /**
00101        *  @brief  Construct a %shared_ptr that owns the pointer @a __p.
00102        *  @param  __p  A pointer that is convertible to element_type*.
00103        *  @post   use_count() == 1 && get() == __p
00104        *  @throw  std::bad_alloc, in which case @c delete @a __p is called.
00105        */
00106       template<typename _Tp1>
00107     explicit shared_ptr(_Tp1* __p) : __shared_ptr<_Tp>(__p) { }
00108 
00109       /**
00110        *  @brief  Construct a %shared_ptr that owns the pointer @a __p
00111        *          and the deleter @a __d.
00112        *  @param  __p  A pointer.
00113        *  @param  __d  A deleter.
00114        *  @post   use_count() == 1 && get() == __p
00115        *  @throw  std::bad_alloc, in which case @a __d(__p) is called.
00116        *
00117        *  Requirements: _Deleter's copy constructor and destructor must
00118        *  not throw
00119        *
00120        *  __shared_ptr will release __p by calling __d(__p)
00121        */
00122       template<typename _Tp1, typename _Deleter>
00123     shared_ptr(_Tp1* __p, _Deleter __d) : __shared_ptr<_Tp>(__p, __d) { }
00124 
00125       /**
00126        *  @brief  Construct a %shared_ptr that owns a null pointer
00127        *          and the deleter @a __d.
00128        *  @param  __p  A null pointer constant.
00129        *  @param  __d  A deleter.
00130        *  @post   use_count() == 1 && get() == __p
00131        *  @throw  std::bad_alloc, in which case @a __d(__p) is called.
00132        *
00133        *  Requirements: _Deleter's copy constructor and destructor must
00134        *  not throw
00135        *
00136        *  The last owner will call __d(__p)
00137        */
00138       template<typename _Deleter>
00139     shared_ptr(nullptr_t __p, _Deleter __d)
00140         : __shared_ptr<_Tp>(__p, __d) { }
00141 
00142       /**
00143        *  @brief  Construct a %shared_ptr that owns the pointer @a __p
00144        *          and the deleter @a __d.
00145        *  @param  __p  A pointer.
00146        *  @param  __d  A deleter.
00147        *  @param  __a  An allocator.
00148        *  @post   use_count() == 1 && get() == __p
00149        *  @throw  std::bad_alloc, in which case @a __d(__p) is called.
00150        *
00151        *  Requirements: _Deleter's copy constructor and destructor must
00152        *  not throw _Alloc's copy constructor and destructor must not
00153        *  throw.
00154        *
00155        *  __shared_ptr will release __p by calling __d(__p)
00156        */
00157       template<typename _Tp1, typename _Deleter, typename _Alloc>
00158     shared_ptr(_Tp1* __p, _Deleter __d, const _Alloc& __a)
00159     : __shared_ptr<_Tp>(__p, __d, __a) { }
00160 
00161       /**
00162        *  @brief  Construct a %shared_ptr that owns a null pointer
00163        *          and the deleter @a __d.
00164        *  @param  __p  A null pointer constant.
00165        *  @param  __d  A deleter.
00166        *  @param  __a  An allocator.
00167        *  @post   use_count() == 1 && get() == __p
00168        *  @throw  std::bad_alloc, in which case @a __d(__p) is called.
00169        *
00170        *  Requirements: _Deleter's copy constructor and destructor must
00171        *  not throw _Alloc's copy constructor and destructor must not
00172        *  throw.
00173        *
00174        *  The last owner will call __d(__p)
00175        */
00176       template<typename _Deleter, typename _Alloc>
00177     shared_ptr(nullptr_t __p, _Deleter __d, const _Alloc& __a)
00178     : __shared_ptr<_Tp>(__p, __d, __a) { }
00179 
00180       // Aliasing constructor
00181 
00182       /**
00183        *  @brief  Constructs a %shared_ptr instance that stores @a __p
00184        *          and shares ownership with @a __r.
00185        *  @param  __r  A %shared_ptr.
00186        *  @param  __p  A pointer that will remain valid while @a *__r is valid.
00187        *  @post   get() == __p && use_count() == __r.use_count()
00188        *
00189        *  This can be used to construct a @c shared_ptr to a sub-object
00190        *  of an object managed by an existing @c shared_ptr.
00191        *
00192        * @code
00193        * shared_ptr< pair<int,int> > pii(new pair<int,int>());
00194        * shared_ptr<int> pi(pii, &pii->first);
00195        * assert(pii.use_count() == 2);
00196        * @endcode
00197        */
00198       template<typename _Tp1>
00199     shared_ptr(const shared_ptr<_Tp1>& __r, _Tp* __p)
00200     : __shared_ptr<_Tp>(__r, __p) { }
00201 
00202       /**
00203        *  @brief  If @a __r is empty, constructs an empty %shared_ptr;
00204        *          otherwise construct a %shared_ptr that shares ownership
00205        *          with @a __r.
00206        *  @param  __r  A %shared_ptr.
00207        *  @post   get() == __r.get() && use_count() == __r.use_count()
00208        */
00209       template<typename _Tp1>
00210     shared_ptr(const shared_ptr<_Tp1>& __r) : __shared_ptr<_Tp>(__r) { }
00211 
00212       /**
00213        *  @brief  Move-constructs a %shared_ptr instance from @a __r.
00214        *  @param  __r  A %shared_ptr rvalue.
00215        *  @post   *this contains the old value of @a __r, @a __r is empty.
00216        */
00217       shared_ptr(shared_ptr&& __r)
00218       : __shared_ptr<_Tp>(std::move(__r)) { }
00219 
00220       /**
00221        *  @brief  Move-constructs a %shared_ptr instance from @a __r.
00222        *  @param  __r  A %shared_ptr rvalue.
00223        *  @post   *this contains the old value of @a __r, @a __r is empty.
00224        */
00225       template<typename _Tp1>
00226     shared_ptr(shared_ptr<_Tp1>&& __r)
00227     : __shared_ptr<_Tp>(std::move(__r)) { }
00228 
00229       /**
00230        *  @brief  Constructs a %shared_ptr that shares ownership with @a __r
00231        *          and stores a copy of the pointer stored in @a __r.
00232        *  @param  __r  A weak_ptr.
00233        *  @post   use_count() == __r.use_count()
00234        *  @throw  bad_weak_ptr when __r.expired(),
00235        *          in which case the constructor has no effect.
00236        */
00237       template<typename _Tp1>
00238     explicit shared_ptr(const weak_ptr<_Tp1>& __r)
00239     : __shared_ptr<_Tp>(__r) { }
00240 
00241 #if _GLIBCXX_DEPRECATED
00242       template<typename _Tp1>
00243     shared_ptr(std::auto_ptr<_Tp1>&& __r)
00244     : __shared_ptr<_Tp>(std::move(__r)) { }
00245 #endif
00246 
00247       template<typename _Tp1, typename _Del>
00248     shared_ptr(std::unique_ptr<_Tp1, _Del>&& __r)
00249     : __shared_ptr<_Tp>(std::move(__r)) { }
00250 
00251       /**
00252        *  @brief  Construct an empty %shared_ptr.
00253        *  @param  __p  A null pointer constant.
00254        *  @post   use_count() == 0 && get() == nullptr
00255        */
00256       shared_ptr(nullptr_t __p) : __shared_ptr<_Tp>(__p) { }
00257 
00258       template<typename _Tp1>
00259     shared_ptr&
00260     operator=(const shared_ptr<_Tp1>& __r) // never throws
00261     {
00262       this->__shared_ptr<_Tp>::operator=(__r);
00263       return *this;
00264     }
00265 
00266 #if _GLIBCXX_DEPRECATED
00267       template<typename _Tp1>
00268     shared_ptr&
00269     operator=(std::auto_ptr<_Tp1>&& __r)
00270     {
00271       this->__shared_ptr<_Tp>::operator=(std::move(__r));
00272       return *this;
00273     }
00274 #endif
00275 
00276       shared_ptr&
00277       operator=(shared_ptr&& __r)
00278       {
00279     this->__shared_ptr<_Tp>::operator=(std::move(__r));
00280     return *this;
00281       }
00282 
00283       template<class _Tp1>
00284     shared_ptr&
00285     operator=(shared_ptr<_Tp1>&& __r)
00286     {
00287       this->__shared_ptr<_Tp>::operator=(std::move(__r));
00288       return *this;
00289     }
00290 
00291       template<typename _Tp1, typename _Del>
00292     shared_ptr&
00293     operator=(std::unique_ptr<_Tp1, _Del>&& __r)
00294     {
00295       this->__shared_ptr<_Tp>::operator=(std::move(__r));
00296       return *this;
00297     }
00298 
00299     private:
00300       // This constructor is non-standard, it is used by allocate_shared.
00301       template<typename _Alloc, typename... _Args>
00302     shared_ptr(_Sp_make_shared_tag __tag, _Alloc __a, _Args&&... __args)
00303     : __shared_ptr<_Tp>(__tag, __a, std::forward<_Args>(__args)...)
00304     { }
00305 
00306       template<typename _Tp1, typename _Alloc, typename... _Args>
00307     friend shared_ptr<_Tp1>
00308     allocate_shared(_Alloc __a, _Args&&... __args);
00309     };
00310 
00311   // 20.8.13.2.7 shared_ptr comparisons
00312   template<typename _Tp1, typename _Tp2>
00313     inline bool
00314     operator==(const shared_ptr<_Tp1>& __a, const shared_ptr<_Tp2>& __b)
00315     { return __a.get() == __b.get(); }
00316 
00317   template<typename _Tp1, typename _Tp2>
00318     inline bool
00319     operator!=(const shared_ptr<_Tp1>& __a, const shared_ptr<_Tp2>& __b)
00320     { return __a.get() != __b.get(); }
00321 
00322   template<typename _Tp1, typename _Tp2>
00323     inline bool
00324     operator<(const shared_ptr<_Tp1>& __a, const shared_ptr<_Tp2>& __b)
00325     { return __a.get() < __b.get(); }
00326 
00327   template<typename _Tp>
00328     struct less<shared_ptr<_Tp>> : public _Sp_less<shared_ptr<_Tp>>
00329     { };
00330 
00331   // 20.8.13.2.9 shared_ptr specialized algorithms.
00332   template<typename _Tp>
00333     inline void
00334     swap(shared_ptr<_Tp>& __a, shared_ptr<_Tp>& __b)
00335     { __a.swap(__b); }
00336 
00337   // 20.8.13.2.10 shared_ptr casts.
00338   template<typename _Tp, typename _Tp1>
00339     inline shared_ptr<_Tp>
00340     static_pointer_cast(const shared_ptr<_Tp1>& __r)
00341     { return shared_ptr<_Tp>(__r, static_cast<_Tp*>(__r.get())); }
00342 
00343   template<typename _Tp, typename _Tp1>
00344     inline shared_ptr<_Tp>
00345     const_pointer_cast(const shared_ptr<_Tp1>& __r)
00346     { return shared_ptr<_Tp>(__r, const_cast<_Tp*>(__r.get())); }
00347 
00348   template<typename _Tp, typename _Tp1>
00349     inline shared_ptr<_Tp>
00350     dynamic_pointer_cast(const shared_ptr<_Tp1>& __r)
00351     {
00352       if (_Tp* __p = dynamic_cast<_Tp*>(__r.get()))
00353     return shared_ptr<_Tp>(__r, __p);
00354       return shared_ptr<_Tp>();
00355     }
00356 
00357 
00358   /**
00359    *  @brief  A smart pointer with weak semantics.
00360    *
00361    *  With forwarding constructors and assignment operators.
00362    */
00363   template<typename _Tp>
00364     class weak_ptr : public __weak_ptr<_Tp>
00365     {
00366     public:
00367       weak_ptr() : __weak_ptr<_Tp>() { }
00368 
00369       template<typename _Tp1>
00370     weak_ptr(const weak_ptr<_Tp1>& __r)
00371     : __weak_ptr<_Tp>(__r) { }
00372 
00373       template<typename _Tp1>
00374     weak_ptr(const shared_ptr<_Tp1>& __r)
00375     : __weak_ptr<_Tp>(__r) { }
00376 
00377       template<typename _Tp1>
00378     weak_ptr&
00379     operator=(const weak_ptr<_Tp1>& __r) // never throws
00380     {
00381       this->__weak_ptr<_Tp>::operator=(__r);
00382       return *this;
00383     }
00384 
00385       template<typename _Tp1>
00386     weak_ptr&
00387     operator=(const shared_ptr<_Tp1>& __r) // never throws
00388     {
00389       this->__weak_ptr<_Tp>::operator=(__r);
00390       return *this;
00391     }
00392 
00393       shared_ptr<_Tp>
00394       lock() const // never throws
00395       {
00396 #ifdef __GTHREADS
00397     if (this->expired())
00398       return shared_ptr<_Tp>();
00399 
00400     __try
00401       {
00402         return shared_ptr<_Tp>(*this);
00403       }
00404     __catch(const bad_weak_ptr&)
00405       {
00406         return shared_ptr<_Tp>();
00407       }
00408 #else
00409     return this->expired() ? shared_ptr<_Tp>() : shared_ptr<_Tp>(*this);
00410 #endif
00411       }
00412     };
00413 
00414   // 20.8.13.3.7 weak_ptr specialized algorithms.
00415   template<typename _Tp>
00416     inline void
00417     swap(weak_ptr<_Tp>& __a, weak_ptr<_Tp>& __b)
00418     { __a.swap(__b); }
00419 
00420 
00421   /// Primary template owner_less
00422   template<typename _Tp>
00423     struct owner_less;
00424 
00425   /// Partial specialization of owner_less for shared_ptr.
00426   template<typename _Tp>
00427     struct owner_less<shared_ptr<_Tp>>
00428     : public _Sp_owner_less<shared_ptr<_Tp>, weak_ptr<_Tp>>
00429     { };
00430 
00431   /// Partial specialization of owner_less for weak_ptr.
00432   template<typename _Tp>
00433     struct owner_less<weak_ptr<_Tp>>
00434     : public _Sp_owner_less<weak_ptr<_Tp>, shared_ptr<_Tp>>
00435     { };
00436 
00437   /**
00438    *  @brief Base class allowing use of member function shared_from_this.
00439    */
00440   template<typename _Tp>
00441     class enable_shared_from_this
00442     {
00443     protected:
00444       enable_shared_from_this() { }
00445 
00446       enable_shared_from_this(const enable_shared_from_this&) { }
00447 
00448       enable_shared_from_this&
00449       operator=(const enable_shared_from_this&)
00450       { return *this; }
00451 
00452       ~enable_shared_from_this() { }
00453 
00454     public:
00455       shared_ptr<_Tp>
00456       shared_from_this()
00457       { return shared_ptr<_Tp>(this->_M_weak_this); }
00458 
00459       shared_ptr<const _Tp>
00460       shared_from_this() const
00461       { return shared_ptr<const _Tp>(this->_M_weak_this); }
00462 
00463     private:
00464       template<typename _Tp1>
00465     void
00466     _M_weak_assign(_Tp1* __p, const __shared_count<>& __n) const
00467     { _M_weak_this._M_assign(__p, __n); }
00468 
00469       template<typename _Tp1>
00470     friend void
00471     __enable_shared_from_this_helper(const __shared_count<>& __pn,
00472                      const enable_shared_from_this* __pe,
00473                      const _Tp1* __px)
00474     {
00475       if (__pe != 0)
00476         __pe->_M_weak_assign(const_cast<_Tp1*>(__px), __pn);
00477     }
00478 
00479       mutable weak_ptr<_Tp>  _M_weak_this;
00480     };
00481 
00482   /**
00483    *  @brief  Create an object that is owned by a shared_ptr.
00484    *  @param  __a     An allocator.
00485    *  @param  __args  Arguments for the @a _Tp object's constructor.
00486    *  @return A shared_ptr that owns the newly created object.
00487    *  @throw  An exception thrown from @a _Alloc::allocate or from the
00488    *          constructor of @a _Tp.
00489    *
00490    *  A copy of @a __a will be used to allocate memory for the shared_ptr
00491    *  and the new object.
00492    */
00493   template<typename _Tp, typename _Alloc, typename... _Args>
00494     inline shared_ptr<_Tp>
00495     allocate_shared(_Alloc __a, _Args&&... __args)
00496     {
00497       return shared_ptr<_Tp>(_Sp_make_shared_tag(), std::forward<_Alloc>(__a),
00498                  std::forward<_Args>(__args)...);
00499     }
00500 
00501   /**
00502    *  @brief  Create an object that is owned by a shared_ptr.
00503    *  @param  __args  Arguments for the @a _Tp object's constructor.
00504    *  @return A shared_ptr that owns the newly created object.
00505    *  @throw  std::bad_alloc, or an exception thrown from the
00506    *          constructor of @a _Tp.
00507    */
00508   template<typename _Tp, typename... _Args>
00509     inline shared_ptr<_Tp>
00510     make_shared(_Args&&... __args)
00511     {
00512       typedef typename std::remove_const<_Tp>::type _Tp_nc;
00513       return allocate_shared<_Tp>(std::allocator<_Tp_nc>(),
00514                   std::forward<_Args>(__args)...);
00515     }
00516 
00517   /// std::hash specialization for shared_ptr.
00518   template<typename _Tp>
00519     struct hash<shared_ptr<_Tp>>
00520     : public std::unary_function<shared_ptr<_Tp>, size_t>
00521     {
00522       size_t
00523       operator()(const shared_ptr<_Tp>& __s) const
00524       { return std::hash<_Tp*>()(__s.get()); }
00525     };
00526 
00527   // @} group pointer_abstractions
00528 
00529 _GLIBCXX_END_NAMESPACE
00530 
00531 #endif // _SHARED_PTR_H