added wxWeakRef<T> (slightly modified patch 1860953)
[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 wxWeakRef(T *pobj = NULL) : m_pobj(NULL) { Assign(pobj); }
23
24 virtual ~wxWeakRef() { Assign(NULL); }
25
26 // Smart pointer functions
27 operator T*(){ return m_pobj; }
28 T* operator->(){ return m_pobj; }
29 T* operator=(T *pobj)
30 {
31 Assign(pobj);
32 return m_pobj;
33 }
34
35 virtual void OnObjectDestroy()
36 {
37 // Tracked object itself removes us from list of trackers
38 wxASSERT( m_pobj );
39 m_pobj = NULL;
40 }
41
42 virtual wxTrackerNodeType GetType() { return WeakRef; }
43
44 protected:
45 wxTrackableBase *GetTrackable(T *pobj)
46 {
47 // this uses static_cast if possible or dynamic_cast otherwise
48 return wxTrackableCaster<T, wxHasBase<T, wxTrackableBase>::value>
49 ::Cast(pobj);
50 }
51
52 void Assign(T* pobj)
53 {
54 if ( m_pobj == pobj )
55 return;
56
57 // First release old object if any
58 if ( m_pobj )
59 {
60 // Remove ourselves from object tracker list
61 GetTrackable(m_pobj)->RemoveNode(this);
62 m_pobj = NULL;
63 }
64
65 // Now set new trackable object
66 if ( pobj )
67 {
68 wxTrackableBase * const pt = GetTrackable(pobj);
69 wxCHECK_RET( pt, "type must derive from wxTrackableBase" );
70
71 pt->AddNode(this);
72 m_pobj = pobj;
73 }
74 }
75
76 T *m_pobj;
77 };
78
79 // Provide some basic types of weak references
80 class WXDLLIMPEXP_FWD_BASE wxObject;
81 class WXDLLIMPEXP_FWD_BASE wxEvtHandler;
82 class WXDLLIMPEXP_FWD_CORE wxWindow;
83
84 typedef wxWeakRef<wxObject> wxObjectRef;
85 typedef wxWeakRef<wxEvtHandler> wxEvtHandlerRef;
86 typedef wxWeakRef<wxWindow> wxWindowRef;
87
88 #endif // _WX_WEAKREF_H_
89