Updated wxWeakRef<T> to patch Weak references for wx - part 2, removed T*() and added...
[wxWidgets.git] / include / wx / weakref.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wx/weakref.h
3 // Purpose: wxWeakRef - Generic weak references for wxWidgets
4 // Author: Arne Steinarson
5 // Created: 2007-12-27
6 // RCS-ID: $Id$
7 // Copyright: (c) 2007 Arne Steinarson
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 #ifndef _WX_WEAKREF_H_
12 #define _WX_WEAKREF_H_
13
14 #include <wx/tracker.h>
15
16 // A weak reference to an object of type T, where T has type wxTrackable
17 // as one of its base classes (in a static or dynamic sense).
18 template<class T>
19 class wxWeakRef : public wxTrackerNode
20 {
21 public:
22 typedef T element_type;
23
24 wxWeakRef(T *pobj = NULL) : m_pobj(NULL) { Assign(pobj); }
25
26 virtual ~wxWeakRef() { Assign(NULL); }
27
28 T * get() const
29 {
30 return m_pobj;
31 }
32
33 T* operator->()
34 {
35 wxASSERT(m_pobj != NULL);
36 return m_pobj;
37 }
38
39 T& operator*() const
40 {
41 wxASSERT(m_pobj != NULL);
42 return *m_pobj;
43 }
44
45 T* operator=(T *pobj)
46 {
47 Assign(pobj);
48 return m_pobj;
49 }
50
51 // Assign from another weak ref, point to same object
52 T* operator = (const wxWeakRef<T> &wr)
53 {
54 Assign(wr);
55 return m_pobj;
56 }
57
58 virtual void OnObjectDestroy()
59 {
60 // Tracked object itself removes us from list of trackers
61 wxASSERT( m_pobj );
62 m_pobj = NULL;
63 }
64
65 protected:
66 friend class wxTrackableBase;
67 friend class wxEvtHandler;
68
69 virtual wxTrackerNodeType GetType() { return WeakRef; }
70
71 void Assign(T* pobj)
72 {
73 if ( m_pobj == pobj )
74 return;
75
76 // First release old object if any
77 if ( m_pobj )
78 {
79 // Remove ourselves from object tracker list
80 // This does static_cast if available, otherwise it tries dynamic cast
81 wxTrackableBase *pt = wxTrackableCaster<T,wxHasBase<T,wxTrackableBase>::value >::Cast(m_pobj);
82 wxASSERT(pt);
83 pt->RemoveNode(this);
84 m_pobj = NULL;
85 }
86
87 // Now set new trackable object
88 if ( pobj )
89 {
90 wxTrackableBase *pt = wxTrackableCaster<T,wxHasBase<T,wxTrackableBase>::value >::Cast(pobj);
91 if( pt )
92 {
93 pt->AddNode( this );
94 m_pobj = pobj;
95 }
96 else
97 {
98 // If the tracked we want to track does not support wxTackableBase, then
99 // log a message and keep the NULL object pointer.
100 wxLogWarning( _T("wxWeakRef::Assign - Type does not provide wxTrackableBase - resetting tracked object") );
101 }
102 }
103 }
104
105 T *m_pobj;
106 };
107
108 // Provide some basic types of weak references
109 class WXDLLIMPEXP_FWD_BASE wxObject;
110 class WXDLLIMPEXP_FWD_BASE wxEvtHandler;
111 class WXDLLIMPEXP_FWD_CORE wxWindow;
112
113 typedef wxWeakRef<wxObject> wxObjectRef;
114 typedef wxWeakRef<wxEvtHandler> wxEvtHandlerRef;
115 typedef wxWeakRef<wxWindow> wxWindowRef;
116
117 #endif // _WX_WEAKREF_H_
118