cartobase
5.0.5
|
Base class for reference counted objects (intrusive) More...
#include <cartobase/smart/rcptr.h>
Public Types | |
typedef int | RefCounterType |
Public Member Functions | |
RCObject () | |
RCObject (const RCObject &) | |
RCObject & | operator= (const RCObject &) |
virtual | ~RCObject () |
Friends | |
template<class T > | |
class | ref |
template<class T > | |
class | const_ref |
template<class T > | |
class | shared_ptr |
class | rc_ptr_trick |
Base class for reference counted objects (intrusive)
RCObject implements the reference counted object idiom. It allows the building of several Ref (see const_ref
) with the same pointer.
Full description of the reference counted idiom in:
Scott Meyers More Effective C++: 35 New Ways to Improve Your Programs and Designs Addison Wesley 1996 Item 29
Full description of the observer/subject pattern in:
Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides Design Patterns: Elements of Reusable Object-Oriented Software Addison Wesley 1995 pp. 293-303
In some cases it can be necessary to build a Ref from a pointer to an already allocated object. This operation is allowed if and only if the object class derives from RCObject
.
Here is an example of what must not be done. The following program build a Window
class that has a static member named shownWindows
which contains a list of all shown windows. The show()
method must add a reference to this
in the shown windows list. The program will compile but it will crash because the Window
object will be destroyed several times. The problem is that the ref<Window>
created in main()
and the one created in Window::show()
are in different scope. Therefore they have no way to know about eachother existence. Thus, each ref<Window>
will use its own reference counter and both will destroy the Window
upon destruction.
To avoid this problem, it is necessary to include the reference counter in the referenced object class (Window
in our example). This is done by public inheritance of the class RCObject
. Therefore, the right version of the program is slightly different from the bad one :
virtual
inheritance of RCObject
to have exactly one reference counter in all derived classes.T
is derived from RCObject
, the constructors and destructors of ref<T>
and const_ref<T>
are redefined. This is done statically (at compile time). The Ref mecanism does not use any virtual function member. typedef int carto::RCObject::RefCounterType |
Definition at line 140 of file rcptr.h.
Referenced by carto::MutexedObject::operator=().
|
friend |
|
friend |