1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: interface of wxRefCounter
4 // Author: wxWidgets team
5 // Licence: wxWindows licence
6 /////////////////////////////////////////////////////////////////////////////
8 /** @class wxObjectRefData
10 This class is just a typedef to wxRefCounter and is used by wxObject.
12 Derive classes from this to store your own data in wxObject-derived
13 classes. When retrieving information from a wxObject's reference data,
14 you will need to cast to your own derived class.
16 Below is an example illustrating how to store reference counted
17 data in a class derived from wxObject including copy-on-write
20 @section objectrefdata_example Example
26 class MyCar : public wxObject
32 bool IsOk() const { return m_refData != NULL; }
34 bool operator == ( const MyCar& car ) const;
35 bool operator != (const MyCar& car) const { return !(*this == car); }
37 void SetPrice( int price );
41 virtual wxObjectRefData *CreateRefData() const;
42 virtual wxObjectRefData *CloneRefData(const wxObjectRefData *data) const;
44 wxDECLARE_DYNAMIC_CLASS(MyCar)
51 // the reference data class is typically a private class only visible in the
52 // implementation source file of the refcounted class.
53 class MyCarRefData : public wxObjectRefData
61 MyCarRefData( const MyCarRefData& data )
64 // copy refcounted data; this is usually a time- and memory-consuming operation
65 // and is only done when two (or more) MyCar instances need to unshare a
66 // common instance of MyCarRefData
67 m_price = data.m_price;
70 bool operator == (const MyCarRefData& data) const
72 return m_price == data.m_price;
76 // in real world, reference counting is usually used only when
77 // the wxObjectRefData-derived class holds data very memory-consuming;
78 // in this example the various MyCar instances may share a MyCarRefData
79 // instance which however only takes 4 bytes for this integer!
84 #define M_CARDATA ((MyCarRefData *)m_refData)
85 wxIMPLEMENT_DYNAMIC_CLASS(MyCar, wxObject);
87 MyCar::MyCar( int price )
89 // here we init the MyCar internal data:
90 m_refData = new MyCarRefData();
91 M_CARDATA->m_price = price;
94 wxObjectRefData *MyCar::CreateRefData() const
96 return new MyCarRefData;
99 wxObjectRefData *MyCar::CloneRefData(const wxObjectRefData *data) const
101 return new MyCarRefData(*(MyCarRefData *)data);
104 bool MyCar::operator == ( const MyCar& car ) const
106 if (m_refData == car.m_refData)
108 if (!m_refData || !car.m_refData)
111 // here we use the MyCarRefData::operator==() function.
112 // Note however that this comparison may be very slow if the
113 // reference data contains a lot of data to be compared.
114 return ( *(MyCarRefData*)m_refData == *(MyCarRefData*)car.m_refData );
117 void MyCar::SetPrice( int price )
119 // since this function modifies one of the MyCar internal property,
120 // we need to be sure that the other MyCar instances which share the
121 // same MyCarRefData instance are not affected by this call.
122 // I.e. it's very important to call UnShare() in all setters of
123 // refcounted classes!
126 M_CARDATA->m_price = price;
129 int MyCar::GetPrice() const
131 wxCHECK_MSG( IsOk(), -1, "invalid car" );
133 return M_CARDATA->m_price;
141 @see wxObject, wxObjectDataPtr<T>, @ref overview_refcount
143 typedef wxRefCounter wxObjectRefData
;
149 This class is used to manage reference-counting providing a simple
150 interface and a counter. wxRefCounter can be easily used together
151 with wxObjectDataPtr<T> to ensure that no calls to wxRefCounter::DecRef()
152 are missed - thus avoiding memory leaks.
154 wxObjectRefData is a typedef to wxRefCounter and is used as the
155 built-in reference counted storage for wxObject-derived classes.
160 @see wxObject, wxObjectRefData, wxObjectDataPtr<T>, @ref overview_refcount
168 It's declared @c protected so that wxRefCounter instances
169 will never be destroyed directly but only as result of a DecRef() call.
171 virtual ~wxRefCounter();
175 Default constructor. Initialises the internal reference count to 1.
180 Decrements the reference count associated with this shared data and, if
181 it reaches zero, destroys this instance of wxRefCounter releasing its
184 Please note that after calling this function, the caller should
185 absolutely avoid to use the pointer to this instance since it may not be
191 Returns the reference count associated with this shared data.
193 When this goes to zero during a DecRef() call, the object will auto-free itself.
195 int GetRefCount() const;
198 Increments the reference count associated with this shared data.
208 This is the root class of many of the wxWidgets classes.
210 It declares a virtual destructor which ensures that destructors get called
211 for all derived class objects where necessary.
213 wxObject is the hub of a dynamic object creation scheme, enabling a program
214 to create instances of a class only knowing its string class name, and to
215 query the class hierarchy.
217 The class contains optional debugging versions of @b new and @b delete, which
218 can help trace memory allocation and deallocation problems.
220 wxObject can be used to implement @ref overview_refcount "reference counted"
221 objects, such as wxPen, wxBitmap and others
222 (see @ref overview_refcount_list "this list").
223 See wxRefCounter and @ref overview_refcount for more info about
229 @see wxClassInfo, @ref overview_debugging, @ref overview_refcount,
230 wxObjectDataRef, wxObjectDataPtr<T>
237 Default ctor; initializes to @NULL the internal reference data.
244 Sets the internal wxObject::m_refData pointer to point to the same
245 instance of the wxObjectRefData-derived class pointed by @c other and
246 increments the refcount of wxObject::m_refData.
248 wxObject(const wxObject
& other
);
253 Performs dereferencing, for those objects that use reference counting.
258 This virtual function is redefined for every class that requires run-time
259 type information, when using the ::wxDECLARE_CLASS macro (or similar).
261 virtual wxClassInfo
* GetClassInfo() const;
264 Returns the wxObject::m_refData pointer, i.e.\ the data referenced by this object.
266 @see Ref(), UnRef(), wxObject::m_refData, SetRefData(), wxObjectRefData
268 wxObjectRefData
* GetRefData() const;
271 Determines whether this class is a subclass of (or the same class as)
277 bool tmp = obj->IsKindOf(wxCLASSINFO(wxFrame));
281 A pointer to a class information object, which may be obtained
282 by using the ::wxCLASSINFO macro.
284 @return @true if the class represented by info is the same class as this
285 one or is derived from it.
287 bool IsKindOf(const wxClassInfo
* info
) const;
290 Returns @true if this object has the same data pointer as @a obj.
292 Notice that @true is returned if the data pointers are @NULL in both objects.
294 This function only does a @e shallow comparison, i.e. it doesn't compare
295 the objects pointed to by the data pointers of these objects.
297 @see @ref overview_refcount
299 bool IsSameAs(const wxObject
& obj
) const;
302 Makes this object refer to the data in @a clone.
305 The object to 'clone'.
307 @remarks First this function calls UnRef() on itself to decrement
308 (and perhaps free) the data it is currently referring to.
309 It then sets its own wxObject::m_refData to point to that of @a clone,
310 and increments the reference count inside the data.
312 @see UnRef(), SetRefData(), GetRefData(), wxObjectRefData
314 void Ref(const wxObject
& clone
);
317 Sets the wxObject::m_refData pointer.
319 @see Ref(), UnRef(), GetRefData(), wxObjectRefData
321 void SetRefData(wxObjectRefData
* data
);
324 Decrements the reference count in the associated data, and if it is zero,
327 The wxObject::m_refData member is set to @NULL.
329 @see Ref(), SetRefData(), GetRefData(), wxObjectRefData
334 This is the same of AllocExclusive() but this method is public.
339 The @e delete operator is defined for debugging versions of the library only,
340 when the identifier @c __WXDEBUG__ is defined.
342 It takes over memory deallocation, allowing wxDebugContext operations.
344 void operator delete(void *buf
);
347 The @e new operator is defined for debugging versions of the library only, when
348 the identifier @c __WXDEBUG__ is defined.
350 It takes over memory allocation, allowing wxDebugContext operations.
352 void* operator new(size_t size
, const wxString
& filename
= NULL
, int lineNum
= 0);
356 Ensure that this object's data is not shared with any other object.
358 If we have no data, it is created using CreateRefData();
359 if we have shared data (i.e. data with a reference count greater than 1),
360 it is copied using CloneRefData(); otherwise nothing is done (the data
361 is already present and is not shared by other object instances).
363 If you use this function you should make sure that you override the
364 CreateRefData() and CloneRefData() functions in your class otherwise
365 an assertion will fail at runtime.
367 void AllocExclusive();
370 Creates a new instance of the wxObjectRefData-derived class specific to
371 this object and returns it.
373 This is usually implemented as a one-line call:
375 wxObjectRefData *MyObject::CreateRefData() const
377 return new MyObjectRefData;
381 virtual wxObjectRefData
*CreateRefData() const;
384 Creates a new instance of the wxObjectRefData-derived class specific to
385 this object and initializes it copying @a data.
387 This is usually implemented as a one-line call:
389 wxObjectRefData *MyObject::CloneRefData(const wxObjectRefData *data) const
391 // rely on the MyObjectRefData copy ctor:
392 return new MyObjectRefData(*(MyObjectRefData *)data);
396 virtual wxObjectRefData
*CloneRefData(const wxObjectRefData
*data
) const;
399 Pointer to an object which is the object's reference-counted data.
401 @see Ref(), UnRef(), SetRefData(), GetRefData(), wxObjectRefData
403 wxObjectRefData
* m_refData
;
411 This class stores meta-information about classes.
413 Instances of this class are not generally defined directly by an application,
414 but indirectly through use of macros such as ::wxDECLARE_DYNAMIC_CLASS and
415 ::wxIMPLEMENT_DYNAMIC_CLASS.
420 @see @ref overview_rtti_classinfo, wxObject
426 Constructs a wxClassInfo object.
428 The supplied macros implicitly construct objects of this class, so there is no
429 need to create such objects explicitly in an application.
431 wxClassInfo(const wxChar
* className
,
432 const wxClassInfo
* baseClass1
,
433 const wxClassInfo
* baseClass2
,
434 int size
, wxObjectConstructorFn fn
);
437 Creates an object of the appropriate kind.
439 @return @NULL if the class has not been declared dynamically creatable
440 (typically, this happens for abstract classes).
442 wxObject
* CreateObject() const;
445 Finds the wxClassInfo object for a class with the given @a name.
447 static wxClassInfo
* FindClass(const wxString
& className
);
450 Returns the name of the first base class (@NULL if none).
452 const wxChar
* GetBaseClassName1() const;
455 Returns the name of the second base class (@NULL if none).
457 const wxChar
* GetBaseClassName2() const;
460 Returns the string form of the class name.
462 const wxChar
* GetClassName() const;
465 Returns the size of the class.
470 Returns @true if this class info can create objects of the associated class.
472 bool IsDynamic() const;
475 Returns @true if this class is a kind of (inherits from) the given class.
477 bool IsKindOf(const wxClassInfo
* info
) const;
484 This is an helper template class primarily written to avoid memory leaks because
485 of missing calls to wxRefCounter::DecRef() and wxObjectRefData::DecRef().
487 Despite the name this template can actually be used as a smart pointer for any
488 class implementing the reference counting interface which only consists of the two
489 methods @b T::IncRef() and @b T::DecRef().
491 The difference to wxSharedPtr<T> is that wxObjectDataPtr<T> relies on the reference
492 counting to be in the class pointed to, where instead wxSharedPtr<T> implements the
493 reference counting itself.
495 Below is an example illustrating how to implement reference counted
496 data using wxRefCounter and wxObjectDataPtr<T> with copy-on-write
499 @section objectdataptr_example Example
502 class MyCarRefData: public wxRefCounter
505 MyCarRefData( int price = 0 ) : m_price(price) { }
506 MyCarRefData( const MyCarRefData& data ) : m_price(data.m_price) { }
508 void SetPrice( int price ) { m_price = price; }
509 int GetPrice() const { return m_price; }
518 // initializes this MyCar assigning to the
519 // internal data pointer a new instance of MyCarRefData
520 MyCar( int price = 0 ) : m_data( new MyCarRefData(price) )
524 MyCar& operator =( const MyCar& tocopy )
526 // shallow copy: this is just a fast copy of pointers; the real
527 // memory-consuming data which typically is stored inside
528 // MyCarRefData is not copied here!
529 m_data = tocopy.m_data;
533 bool operator == ( const MyCar& other ) const
535 if (m_data.get() == other.m_data.get())
536 return true; // this instance and the 'other' one share the
537 // same MyCarRefData data...
539 return (m_data.GetPrice() == other.m_data.GetPrice());
542 void SetPrice( int price )
544 // make sure changes to this class do not affect other instances
545 // currently sharing our same refcounted data:
548 m_data->SetPrice( price );
553 return m_data->GetPrice();
556 wxObjectDataPtr<MyCarRefData> m_data;
561 if (m_data->GetRefCount() == 1)
564 m_data.reset( new MyCarRefData( *m_data ) );
571 @category{rtti,smartpointers}
573 @see wxObject, wxObjectRefData, @ref overview_refcount, wxSharedPtr<T>,
574 wxScopedPtr<T>, wxWeakRef<T>
577 class wxObjectDataPtr
<T
>
583 @a ptr is a pointer to the reference counted object to which this class points.
584 If @a ptr is not NULL @b T::IncRef() will be called on the object.
586 wxObjectDataPtr
<T
>(T
* ptr
= NULL
);
589 This copy constructor increases the count of the reference counted object to
590 which @a tocopy points and then this class will point to, as well.
592 wxObjectDataPtr
<T
>(const wxObjectDataPtr
<T
>& tocopy
);
596 Decreases the reference count of the object to which this class points.
598 ~wxObjectDataPtr
<T
>();
601 Gets a pointer to the reference counted object to which this class points.
606 Reset this class to ptr which points to a reference counted object and
607 calls T::DecRef() on the previously owned object.
612 Conversion to a boolean expression (in a variant which is not
613 convertable to anything but a boolean expression).
615 If this class contains a valid pointer it will return @true, if it contains
616 a @NULL pointer it will return @false.
618 operator unspecified_bool_type() const;
621 Returns a reference to the object.
623 If the internal pointer is @NULL this method will cause an assert in debug mode.
625 T
& operator*() const;
628 Returns a pointer to the reference counted object to which this class points.
630 If this the internal pointer is @NULL, this method will assert in debug mode.
632 T
* operator->() const;
638 wxObjectDataPtr
<T
>& operator=(const wxObjectDataPtr
<T
>& tocopy
);
639 wxObjectDataPtr
<T
>& operator=(T
* ptr
);
645 // ============================================================================
646 // Global functions/macros
647 // ============================================================================
649 /** @addtogroup group_funcmacro_rtti */
653 Returns a pointer to the wxClassInfo object associated with this class.
657 #define wxCLASSINFO( className )
660 Used inside a class declaration to declare that the class should be
661 made known to the class hierarchy, but objects of this class cannot be created
669 class wxCommand: public wxObject
671 wxDECLARE_ABSTRACT_CLASS(wxCommand);
680 #define wxDECLARE_ABSTRACT_CLASS( className )
683 Used inside a class declaration to make the class known to wxWidgets RTTI
684 system and also declare that the objects of this class should be
685 dynamically creatable from run-time type information. Notice that this
686 implies that the class should have a default constructor, if this is not
687 the case consider using wxDECLARE_ABSTRACT_CLASS().
694 class wxFrame: public wxWindow
696 wxDECLARE_DYNAMIC_CLASS(wxFrame);
699 const wxString& frameTitle;
705 #define wxDECLARE_DYNAMIC_CLASS( className )
708 Used inside a class declaration to declare that the class should be made
709 known to the class hierarchy, but objects of this class cannot be created
712 The same as wxDECLARE_ABSTRACT_CLASS().
716 #define wxDECLARE_CLASS( className )
719 Used in a C++ implementation file to complete the declaration of a class
720 that has run-time type information.
727 wxIMPLEMENT_ABSTRACT_CLASS(wxCommand, wxObject);
729 wxCommand::wxCommand(void)
735 #define wxIMPLEMENT_ABSTRACT_CLASS( className, baseClassName )
738 Used in a C++ implementation file to complete the declaration of a class
739 that has run-time type information and two base classes.
743 #define wxIMPLEMENT_ABSTRACT_CLASS2( className, baseClassName1, baseClassName2 )
746 Used in a C++ implementation file to complete the declaration of a class
747 that has run-time type information, and whose instances can be created
755 wxIMPLEMENT_DYNAMIC_CLASS(wxFrame, wxWindow);
757 wxFrame::wxFrame(void)
763 #define wxIMPLEMENT_DYNAMIC_CLASS( className, baseClassName )
766 Used in a C++ implementation file to complete the declaration of a class
767 that has run-time type information, and whose instances can be created
768 dynamically. Use this for classes derived from two base classes.
772 #define wxIMPLEMENT_DYNAMIC_CLASS2( className, baseClassName1, baseClassName2 )
775 Used in a C++ implementation file to complete the declaration of a class
776 that has run-time type information, and whose instances can be created
777 dynamically. The same as wxIMPLEMENT_DYNAMIC_CLASS().
781 #define wxIMPLEMENT_CLASS( className, baseClassName )
784 Used in a C++ implementation file to complete the declaration of a class
785 that has run-time type information and two base classes, and whose instances
786 can be created dynamically. The same as wxIMPLEMENT_DYNAMIC_CLASS2().
790 #define wxIMPLEMENT_CLASS2( className, baseClassName1, baseClassName2 )
793 Same as @c const_cast<T>(x) if the compiler supports const cast or @c (T)x for
794 old compilers. Unlike wxConstCast(), the cast it to the type @c T and not to
795 <tt>T *</tt> and also the order of arguments is the same as for the standard cast.
799 @see wx_reinterpret_cast(), wx_static_cast()
801 #define wx_const_cast(T, x)
804 Same as @c reinterpret_cast<T>(x) if the compiler supports reinterpret cast or
805 @c (T)x for old compilers.
809 @see wx_const_cast(), wx_static_cast()
811 #define wx_reinterpret_cast(T, x)
814 Same as @c static_cast<T>(x) if the compiler supports static cast or @c (T)x for
815 old compilers. Unlike wxStaticCast(), there are no checks being done and
816 the meaning of the macro arguments is exactly the same as for the standard
817 static cast, i.e. @a T is the full type name and star is not appended to it.
821 @see wx_const_cast(), wx_reinterpret_cast(), wx_truncate_cast()
823 #define wx_static_cast(T, x)
826 This case doesn’t correspond to any standard cast but exists solely to make
827 casts which possibly result in a truncation of an integer value more
832 #define wx_truncate_cast(T, x)
835 This macro expands into <tt>const_cast<classname *>(ptr)</tt> if the compiler
836 supports const_cast or into an old, C-style cast, otherwise.
840 @see wx_const_cast(), wxDynamicCast(), wxStaticCast()
842 #define wxConstCast( ptr, classname )
845 This macro returns the pointer @e ptr cast to the type @e classname * if
846 the pointer is of this type (the check is done during the run-time) or
847 @NULL otherwise. Usage of this macro is preferred over obsoleted
848 wxObject::IsKindOf() function.
850 The @e ptr argument may be @NULL, in which case @NULL will be returned.
857 wxWindow *win = wxWindow::FindFocus();
858 wxTextCtrl *text = wxDynamicCast(win, wxTextCtrl);
861 // a text control has the focus...
865 // no window has the focus or it is not a text control
869 @see @ref overview_rtti, wxDynamicCastThis(), wxConstCast(), wxStaticCast()
871 #define wxDynamicCast( ptr, classname )
874 This macro is equivalent to <tt>wxDynamicCast(this, classname)</tt> but the latter provokes
875 spurious compilation warnings from some compilers (because it tests whether
876 @c this pointer is non-@NULL which is always true), so this macro should be
883 #define wxDynamicCastThis( classname )
886 This macro checks that the cast is valid in debug mode (an assert failure
887 will result if wxDynamicCast(ptr, classname) == @NULL) and then returns the
888 result of executing an equivalent of <tt>static_cast<classname *>(ptr)</tt>.
892 @see wx_static_cast(), wxDynamicCast(), wxConstCast()
894 #define wxStaticCast( ptr, classname )
897 Creates and returns an object of the given class, if the class has been
898 registered with the dynamic class system using DECLARE... and IMPLEMENT...
903 wxObject
*wxCreateDynamicObject(const wxString
& className
);
907 /** @addtogroup group_funcmacro_debug */
911 This is defined in debug mode to be call the redefined new operator
912 with filename and line number arguments. The definition is:
915 #define WXDEBUG_NEW new(__FILE__,__LINE__)
918 In non-debug mode, this is defined as the normal new operator.
922 #define WXDEBUG_NEW( arg )