]>
git.saurik.com Git - wxWidgets.git/blob - include/wx/sharedptr.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wx/sharedptr.h
3 // Purpose: Shared pointer based on the counted_ptr<> template, which
4 // is in the public domain
5 // Author: Robert Roebling, Yonat Sharon
6 // Copyright: Robert Roebling
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 #ifndef _WX_SHAREDPTR_H_
11 #define _WX_SHAREDPTR_H_
14 #include "wx/atomic.h"
16 // ----------------------------------------------------------------------------
17 // wxSharedPtr: A smart pointer with non-intrusive reference counting.
18 // ----------------------------------------------------------------------------
24 typedef T element_type
;
26 wxEXPLICIT
wxSharedPtr( T
* ptr
= NULL
)
30 m_ref
= new reftype(ptr
);
33 template<typename Deleter
>
34 wxEXPLICIT
wxSharedPtr(T
* ptr
, Deleter d
)
38 m_ref
= new reftype_with_deleter
<Deleter
>(ptr
, d
);
41 ~wxSharedPtr() { Release(); }
42 wxSharedPtr(const wxSharedPtr
& tocopy
) { Acquire(tocopy
.m_ref
); }
44 wxSharedPtr
& operator=( const wxSharedPtr
& tocopy
)
49 Acquire(tocopy
.m_ref
);
54 wxSharedPtr
& operator=( T
* ptr
)
60 m_ref
= new reftype(ptr
);
65 // test for pointer validity: defining conversion to unspecified_bool_type
66 // and not more obvious bool to avoid implicit conversions to integer types
67 typedef T
*(wxSharedPtr
<T
>::*unspecified_bool_type
)() const;
68 operator unspecified_bool_type() const
70 if (m_ref
&& m_ref
->m_ptr
)
71 return &wxSharedPtr
<T
>::get
;
78 wxASSERT(m_ref
!= NULL
);
79 wxASSERT(m_ref
->m_ptr
!= NULL
);
80 return *(m_ref
->m_ptr
);
85 wxASSERT(m_ref
!= NULL
);
86 wxASSERT(m_ref
->m_ptr
!= NULL
);
92 return m_ref
? m_ref
->m_ptr
: NULL
;
95 void reset( T
* ptr
= NULL
)
99 m_ref
= new reftype(ptr
);
102 template<typename Deleter
>
103 void reset(T
* ptr
, Deleter d
)
107 m_ref
= new reftype_with_deleter
<Deleter
>(ptr
, d
);
110 bool unique() const { return (m_ref
? m_ref
->m_count
== 1 : true); }
111 long use_count() const { return (m_ref
? (long)m_ref
->m_count
: 0); }
117 reftype(T
* ptr
) : m_ptr(ptr
), m_count(1) {}
118 virtual ~reftype() {}
119 virtual void delete_ptr() { delete m_ptr
; }
125 template<typename Deleter
>
126 struct reftype_with_deleter
: public reftype
128 reftype_with_deleter(T
* ptr
, Deleter d
) : reftype(ptr
), m_deleter(d
) {}
129 virtual void delete_ptr() { m_deleter(this->m_ptr
); }
136 void Acquire(reftype
* ref
)
140 wxAtomicInc( ref
->m_count
);
147 if (!wxAtomicDec( m_ref
->m_count
))
157 template <class T
, class U
>
158 bool operator == (wxSharedPtr
<T
> const &a
, wxSharedPtr
<U
> const &b
)
160 return a
.get() == b
.get();
163 template <class T
, class U
>
164 bool operator != (wxSharedPtr
<T
> const &a
, wxSharedPtr
<U
> const &b
)
166 return a
.get() != b
.get();
169 #endif // _WX_SHAREDPTR_H_