1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: interface of wxRefCounter
4 // Author: wxWidgets team
6 // Licence: wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
9 /** @class wxObjectRefData
11 This class is just a typedef to wxRefCounter and is used by wxObject.
13 Derive classes from this to store your own data in wxObject-derived
14 classes. When retrieving information from a wxObject's reference data,
15 you will need to cast to your own derived class.
17 Below is an example illustrating how to store reference counted
18 data in a class derived from wxObject including copy-on-write
21 @section objectrefdata_example Example
27 class MyCar : public wxObject
33 bool IsOk() const { return m_refData != NULL; }
35 bool operator == ( const MyCar& car ) const;
36 bool operator != (const MyCar& car) const { return !(*this == car); }
38 void SetPrice( int price );
42 virtual wxObjectRefData *CreateRefData() const;
43 virtual wxObjectRefData *CloneRefData(const wxObjectRefData *data) const;
45 wxDECLARE_DYNAMIC_CLASS(MyCar)
52 // the reference data class is typically a private class only visible in the
53 // implementation source file of the refcounted class.
54 class MyCarRefData : public wxObjectRefData
62 MyCarRefData( const MyCarRefData& data )
65 // copy refcounted data; this is usually a time- and memory-consuming operation
66 // and is only done when two (or more) MyCar instances need to unshare a
67 // common instance of MyCarRefData
68 m_price = data.m_price;
71 bool operator == (const MyCarRefData& data) const
73 return m_price == data.m_price;
77 // in real world, reference counting is usually used only when
78 // the wxObjectRefData-derived class holds data very memory-consuming;
79 // in this example the various MyCar instances may share a MyCarRefData
80 // instance which however only takes 4 bytes for this integer!
85 #define M_CARDATA ((MyCarRefData *)m_refData)
86 wxIMPLEMENT_DYNAMIC_CLASS(MyCar, wxObject);
88 MyCar::MyCar( int price )
90 // here we init the MyCar internal data:
91 m_refData = new MyCarRefData();
92 M_CARDATA->m_price = price;
95 wxObjectRefData *MyCar::CreateRefData() const
97 return new MyCarRefData;
100 wxObjectRefData *MyCar::CloneRefData(const wxObjectRefData *data) const
102 return new MyCarRefData(*(MyCarRefData *)data);
105 bool MyCar::operator == ( const MyCar& car ) const
107 if (m_refData == car.m_refData)
109 if (!m_refData || !car.m_refData)
112 // here we use the MyCarRefData::operator==() function.
113 // Note however that this comparison may be very slow if the
114 // reference data contains a lot of data to be compared.
115 return ( *(MyCarRefData*)m_refData == *(MyCarRefData*)car.m_refData );
118 void MyCar::SetPrice( int price )
120 // since this function modifies one of the MyCar internal property,
121 // we need to be sure that the other MyCar instances which share the
122 // same MyCarRefData instance are not affected by this call.
123 // I.e. it's very important to call UnShare() in all setters of
124 // refcounted classes!
127 M_CARDATA->m_price = price;
130 int MyCar::GetPrice() const
132 wxCHECK_MSG( IsOk(), -1, "invalid car" );
134 return M_CARDATA->m_price;
142 @see wxObject, wxObjectDataPtr<T>, @ref overview_refcount
144 typedef wxRefCounter wxObjectRefData
;
150 This class is used to manage reference-counting providing a simple
151 interface and a counter. wxRefCounter can be easily used together
152 with wxObjectDataPtr<T> to ensure that no calls to wxRefCounter::DecRef()
153 are missed - thus avoiding memory leaks.
155 wxObjectRefData is a typedef to wxRefCounter and is used as the
156 built-in reference counted storage for wxObject-derived classes.
161 @see wxObject, wxObjectRefData, wxObjectDataPtr<T>, @ref overview_refcount
169 It's declared @c protected so that wxRefCounter instances
170 will never be destroyed directly but only as result of a DecRef() call.
172 virtual ~wxRefCounter();
176 Default constructor. Initialises the internal reference count to 1.
181 Decrements the reference count associated with this shared data and, if
182 it reaches zero, destroys this instance of wxRefCounter releasing its
185 Please note that after calling this function, the caller should
186 absolutely avoid to use the pointer to this instance since it may not be
192 Returns the reference count associated with this shared data.
194 When this goes to zero during a DecRef() call, the object will auto-free itself.
196 int GetRefCount() const;
199 Increments the reference count associated with this shared data.
209 This is the root class of many of the wxWidgets classes.
211 It declares a virtual destructor which ensures that destructors get called
212 for all derived class objects where necessary.
214 wxObject is the hub of a dynamic object creation scheme, enabling a program
215 to create instances of a class only knowing its string class name, and to
216 query the class hierarchy.
218 The class contains optional debugging versions of @b new and @b delete, which
219 can help trace memory allocation and deallocation problems.
221 wxObject can be used to implement @ref overview_refcount "reference counted"
222 objects, such as wxPen, wxBitmap and others
223 (see @ref overview_refcount_list "this list").
224 See wxRefCounter and @ref overview_refcount for more info about
230 @see wxClassInfo, @ref overview_debugging, @ref overview_refcount,
231 wxObjectDataRef, wxObjectDataPtr<T>
238 Default ctor; initializes to @NULL the internal reference data.
245 Sets the internal wxObject::m_refData pointer to point to the same
246 instance of the wxObjectRefData-derived class pointed by @c other and
247 increments the refcount of wxObject::m_refData.
249 wxObject(const wxObject
& other
);
254 Performs dereferencing, for those objects that use reference counting.
259 This virtual function is redefined for every class that requires run-time
260 type information, when using the ::wxDECLARE_CLASS macro (or similar).
262 virtual wxClassInfo
* GetClassInfo() const;
265 Returns the wxObject::m_refData pointer, i.e. the data referenced by this object.
267 @see Ref(), UnRef(), wxObject::m_refData, SetRefData(), wxObjectRefData
269 wxObjectRefData
* GetRefData() const;
272 Determines whether this class is a subclass of (or the same class as)
278 bool tmp = obj->IsKindOf(wxCLASSINFO(wxFrame));
282 A pointer to a class information object, which may be obtained
283 by using the ::wxCLASSINFO macro.
285 @return @true if the class represented by info is the same class as this
286 one or is derived from it.
288 bool IsKindOf(const wxClassInfo
* info
) const;
291 Returns @true if this object has the same data pointer as @a obj.
293 Notice that @true is returned if the data pointers are @NULL in both objects.
295 This function only does a @e shallow comparison, i.e. it doesn't compare
296 the objects pointed to by the data pointers of these objects.
298 @see @ref overview_refcount
300 bool IsSameAs(const wxObject
& obj
) const;
303 Makes this object refer to the data in @a clone.
306 The object to 'clone'.
308 @remarks First this function calls UnRef() on itself to decrement
309 (and perhaps free) the data it is currently referring to.
310 It then sets its own wxObject::m_refData to point to that of @a clone,
311 and increments the reference count inside the data.
313 @see UnRef(), SetRefData(), GetRefData(), wxObjectRefData
315 void Ref(const wxObject
& clone
);
318 Sets the wxObject::m_refData pointer.
320 @see Ref(), UnRef(), GetRefData(), wxObjectRefData
322 void SetRefData(wxObjectRefData
* data
);
325 Decrements the reference count in the associated data, and if it is zero,
328 The wxObject::m_refData member is set to @NULL.
330 @see Ref(), SetRefData(), GetRefData(), wxObjectRefData
335 This is the same of AllocExclusive() but this method is public.
340 The @e delete operator is defined for debugging versions of the library only,
341 when the identifier @c __WXDEBUG__ is defined.
343 It takes over memory deallocation, allowing wxDebugContext operations.
345 void operator delete(void *buf
);
348 The @e new operator is defined for debugging versions of the library only, when
349 the identifier @c __WXDEBUG__ is defined.
351 It takes over memory allocation, allowing wxDebugContext operations.
353 void* operator new(size_t size
, const wxString
& filename
= NULL
, int lineNum
= 0);
357 Ensure that this object's data is not shared with any other object.
359 If we have no data, it is created using CreateRefData();
360 if we have shared data (i.e. data with a reference count greater than 1),
361 it is copied using CloneRefData(); otherwise nothing is done (the data
362 is already present and is not shared by other object instances).
364 If you use this function you should make sure that you override the
365 CreateRefData() and CloneRefData() functions in your class otherwise
366 an assertion will fail at runtime.
368 void AllocExclusive();
371 Creates a new instance of the wxObjectRefData-derived class specific to
372 this object and returns it.
374 This is usually implemented as a one-line call:
376 wxObjectRefData *MyObject::CreateRefData() const
378 return new MyObjectRefData;
382 virtual wxObjectRefData
*CreateRefData() const;
385 Creates a new instance of the wxObjectRefData-derived class specific to
386 this object and initializes it copying @a data.
388 This is usually implemented as a one-line call:
390 wxObjectRefData *MyObject::CloneRefData(const wxObjectRefData *data) const
392 // rely on the MyObjectRefData copy ctor:
393 return new MyObjectRefData(*(MyObjectRefData *)data);
397 virtual wxObjectRefData
*CloneRefData(const wxObjectRefData
*data
) const;
400 Pointer to an object which is the object's reference-counted data.
402 @see Ref(), UnRef(), SetRefData(), GetRefData(), wxObjectRefData
404 wxObjectRefData
* m_refData
;
412 This class stores meta-information about classes.
414 Instances of this class are not generally defined directly by an application,
415 but indirectly through use of macros such as ::wxDECLARE_DYNAMIC_CLASS and
416 ::wxIMPLEMENT_DYNAMIC_CLASS.
421 @see @ref overview_rtti_classinfo, wxObject
427 Constructs a wxClassInfo object.
429 The supplied macros implicitly construct objects of this class, so there is no
430 need to create such objects explicitly in an application.
432 wxClassInfo(const wxChar
* className
,
433 const wxClassInfo
* baseClass1
,
434 const wxClassInfo
* baseClass2
,
435 int size
, wxObjectConstructorFn fn
);
438 Creates an object of the appropriate kind.
440 @return @NULL if the class has not been declared dynamically creatable
441 (typically, this happens for abstract classes).
443 wxObject
* CreateObject() const;
446 Finds the wxClassInfo object for a class with the given @a name.
448 static wxClassInfo
* FindClass(const wxString
& className
);
451 Returns the name of the first base class (@NULL if none).
453 const wxChar
* GetBaseClassName1() const;
456 Returns the name of the second base class (@NULL if none).
458 const wxChar
* GetBaseClassName2() const;
461 Returns the string form of the class name.
463 const wxChar
* GetClassName() const;
466 Returns the size of the class.
471 Returns @true if this class info can create objects of the associated class.
473 bool IsDynamic() const;
476 Returns @true if this class is a kind of (inherits from) the given class.
478 bool IsKindOf(const wxClassInfo
* info
) const;
485 This is an helper template class primarily written to avoid memory leaks because
486 of missing calls to wxRefCounter::DecRef() and wxObjectRefData::DecRef().
488 Despite the name this template can actually be used as a smart pointer for any
489 class implementing the reference counting interface which only consists of the two
490 methods @b T::IncRef() and @b T::DecRef().
492 The difference to wxSharedPtr<T> is that wxObjectDataPtr<T> relies on the reference
493 counting to be in the class pointed to, where instead wxSharedPtr<T> implements the
494 reference counting itself.
496 Below is an example illustrating how to implement reference counted
497 data using wxRefCounter and wxObjectDataPtr<T> with copy-on-write
500 @section objectdataptr_example Example
503 class MyCarRefData: public wxRefCounter
506 MyCarRefData( int price = 0 ) : m_price(price) { }
507 MyCarRefData( const MyCarRefData& data ) : m_price(data.m_price) { }
509 void SetPrice( int price ) { m_price = price; }
510 int GetPrice() const { return m_price; }
519 // initializes this MyCar assigning to the
520 // internal data pointer a new instance of MyCarRefData
521 MyCar( int price = 0 ) : m_data( new MyCarRefData(price) )
525 MyCar& operator =( const MyCar& tocopy )
527 // shallow copy: this is just a fast copy of pointers; the real
528 // memory-consuming data which typically is stored inside
529 // MyCarRefData is not copied here!
530 m_data = tocopy.m_data;
534 bool operator == ( const MyCar& other ) const
536 if (m_data.get() == other.m_data.get())
537 return true; // this instance and the 'other' one share the
538 // same MyCarRefData data...
540 return (m_data.GetPrice() == other.m_data.GetPrice());
543 void SetPrice( int price )
545 // make sure changes to this class do not affect other instances
546 // currently sharing our same refcounted data:
549 m_data->SetPrice( price );
554 return m_data->GetPrice();
557 wxObjectDataPtr<MyCarRefData> m_data;
562 if (m_data->GetRefCount() == 1)
565 m_data.reset( new MyCarRefData( *m_data ) );
572 @category{rtti,smartpointers}
574 @see wxObject, wxObjectRefData, @ref overview_refcount, wxSharedPtr<T>,
575 wxScopedPtr<T>, wxWeakRef<T>
578 class wxObjectDataPtr
<T
>
584 @a ptr is a pointer to the reference counted object to which this class points.
585 If @a ptr is not NULL @b T::IncRef() will be called on the object.
587 wxObjectDataPtr
<T
>(T
* ptr
= NULL
);
590 This copy constructor increases the count of the reference counted object to
591 which @a tocopy points and then this class will point to, as well.
593 wxObjectDataPtr
<T
>(const wxObjectDataPtr
<T
>& tocopy
);
597 Decreases the reference count of the object to which this class points.
599 ~wxObjectDataPtr
<T
>();
602 Gets a pointer to the reference counted object to which this class points.
607 Reset this class to ptr which points to a reference counted object and
608 calls T::DecRef() on the previously owned object.
613 Conversion to a boolean expression (in a variant which is not
614 convertable to anything but a boolean expression).
616 If this class contains a valid pointer it will return @true, if it contains
617 a @NULL pointer it will return @false.
619 operator unspecified_bool_type() const;
622 Returns a reference to the object.
624 If the internal pointer is @NULL this method will cause an assert in debug mode.
626 T
& operator*() const;
629 Returns a pointer to the reference counted object to which this class points.
631 If this the internal pointer is @NULL, this method will assert in debug mode.
633 T
* operator->() const;
639 wxObjectDataPtr
<T
>& operator=(const wxObjectDataPtr
<T
>& tocopy
);
640 wxObjectDataPtr
<T
>& operator=(T
* ptr
);
646 // ============================================================================
647 // Global functions/macros
648 // ============================================================================
650 /** @addtogroup group_funcmacro_rtti */
654 Returns a pointer to the wxClassInfo object associated with this class.
658 #define wxCLASSINFO( className )
661 Used inside a class declaration to declare that the class should be
662 made known to the class hierarchy, but objects of this class cannot be created
670 class wxCommand: public wxObject
672 wxDECLARE_ABSTRACT_CLASS(wxCommand);
681 #define wxDECLARE_ABSTRACT_CLASS( className )
684 Used inside a class declaration to make the class known to wxWidgets RTTI
685 system and also declare that the objects of this class should be
686 dynamically creatable from run-time type information. Notice that this
687 implies that the class should have a default constructor, if this is not
688 the case consider using wxDECLARE_ABSTRACT_CLASS().
695 class wxFrame: public wxWindow
697 wxDECLARE_DYNAMIC_CLASS(wxFrame);
700 const wxString& frameTitle;
706 #define wxDECLARE_DYNAMIC_CLASS( className )
709 Used inside a class declaration to declare that the class should be made
710 known to the class hierarchy, but objects of this class cannot be created
711 dynamically. The same as wxDECLARE_DYNAMIC_CLASS().
715 #define wxDECLARE_CLASS( className )
718 Used in a C++ implementation file to complete the declaration of a class
719 that has run-time type information.
726 wxIMPLEMENT_ABSTRACT_CLASS(wxCommand, wxObject);
728 wxCommand::wxCommand(void)
734 #define wxIMPLEMENT_ABSTRACT_CLASS( className, baseClassName )
737 Used in a C++ implementation file to complete the declaration of a class
738 that has run-time type information and two base classes.
742 #define wxIMPLEMENT_ABSTRACT_CLASS2( className, baseClassName1, baseClassName2 )
745 Used in a C++ implementation file to complete the declaration of a class
746 that has run-time type information, and whose instances can be created
754 wxIMPLEMENT_DYNAMIC_CLASS(wxFrame, wxWindow);
756 wxFrame::wxFrame(void)
762 #define wxIMPLEMENT_DYNAMIC_CLASS( className, baseClassName )
765 Used in a C++ implementation file to complete the declaration of a class
766 that has run-time type information, and whose instances can be created
767 dynamically. Use this for classes derived from two base classes.
771 #define wxIMPLEMENT_DYNAMIC_CLASS2( className, baseClassName1, baseClassName2 )
774 Used in a C++ implementation file to complete the declaration of a class
775 that has run-time type information, and whose instances can be created
776 dynamically. The same as wxIMPLEMENT_DYNAMIC_CLASS().
780 #define wxIMPLEMENT_CLASS( className, baseClassName )
783 Used in a C++ implementation file to complete the declaration of a class
784 that has run-time type information and two base classes, and whose instances
785 can be created dynamically. The same as wxIMPLEMENT_DYNAMIC_CLASS2().
789 #define wxIMPLEMENT_CLASS2( className, baseClassName1, baseClassName2 )
792 Same as @c const_cast<T>(x) if the compiler supports const cast or @c (T)x for
793 old compilers. Unlike wxConstCast(), the cast it to the type @c T and not to
794 <tt>T *</tt> and also the order of arguments is the same as for the standard cast.
798 @see wx_reinterpret_cast(), wx_static_cast()
800 #define wx_const_cast(T, x)
803 Same as @c reinterpret_cast<T>(x) if the compiler supports reinterpret cast or
804 @c (T)x for old compilers.
808 @see wx_const_cast(), wx_static_cast()
810 #define wx_reinterpret_cast(T, x)
813 Same as @c static_cast<T>(x) if the compiler supports static cast or @c (T)x for
814 old compilers. Unlike wxStaticCast(), there are no checks being done and
815 the meaning of the macro arguments is exactly the same as for the standard
816 static cast, i.e. @a T is the full type name and star is not appended to it.
820 @see wx_const_cast(), wx_reinterpret_cast(), wx_truncate_cast()
822 #define wx_static_cast(T, x)
825 This case doesn’t correspond to any standard cast but exists solely to make
826 casts which possibly result in a truncation of an integer value more
831 #define wx_truncate_cast(T, x)
834 This macro expands into <tt>const_cast<classname *>(ptr)</tt> if the compiler
835 supports const_cast or into an old, C-style cast, otherwise.
839 @see wx_const_cast(), wxDynamicCast(), wxStaticCast()
841 #define wxConstCast( ptr, classname )
844 This macro returns the pointer @e ptr cast to the type @e classname * if
845 the pointer is of this type (the check is done during the run-time) or
846 @NULL otherwise. Usage of this macro is preferred over obsoleted
847 wxObject::IsKindOf() function.
849 The @e ptr argument may be @NULL, in which case @NULL will be returned.
856 wxWindow *win = wxWindow::FindFocus();
857 wxTextCtrl *text = wxDynamicCast(win, wxTextCtrl);
860 // a text control has the focus...
864 // no window has the focus or it is not a text control
868 @see @ref overview_rtti, wxDynamicCastThis(), wxConstCast(), wxStaticCast()
870 #define wxDynamicCast( ptr, classname )
873 This macro is equivalent to <tt>wxDynamicCast(this, classname)</tt> but the latter provokes
874 spurious compilation warnings from some compilers (because it tests whether
875 @c this pointer is non-@NULL which is always true), so this macro should be
882 #define wxDynamicCastThis( classname )
885 This macro checks that the cast is valid in debug mode (an assert failure
886 will result if wxDynamicCast(ptr, classname) == @NULL) and then returns the
887 result of executing an equivalent of <tt>static_cast<classname *>(ptr)</tt>.
891 @see wx_static_cast(), wxDynamicCast(), wxConstCast()
893 #define wxStaticCast( ptr, classname )
896 Creates and returns an object of the given class, if the class has been
897 registered with the dynamic class system using DECLARE... and IMPLEMENT...
902 wxObject
*wxCreateDynamicObject(const wxString
& className
);
906 /** @addtogroup group_funcmacro_debug */
910 This is defined in debug mode to be call the redefined new operator
911 with filename and line number arguments. The definition is:
914 #define WXDEBUG_NEW new(__FILE__,__LINE__)
917 In non-debug mode, this is defined as the normal new operator.
921 #define WXDEBUG_NEW( arg )