template<class T>
class carto::const_ref< T >
Constant Ref to an object of class T.
The purpose of this class is to provide a way to reference dynamically allocated objects without worrying about their destruction. To avoid confusion with build-in C++ references we call a Ref an object of class const_ref or ref.
A Ref act as a pointer on a dynamicaly allocated object (with new
). The main difference between a Ref an a pointer is the link that exists between the Ref lifetime and the pointed object lifetime. An object pointed to by a Ref is destroyed when the last Ref pointed to it is destroyed. Therefore a Ref contains two things: a pointer to an object and a reference counter. Each time a Ref is created, the counter is incremented. When a Ref is destroyed, the counter is decremented and if the counter is null, the object is destroyed (with delete
).
A Ref can be used to reference any object created by new
. Therefore it can be used with existing classes.
- Warning
- It is the responssability to the programmer to avoid cyclic references or memory leak can occur. For example, in the following program, the objects of class
A
and B
are never destroyed. #include <iostream>
class A;
class B;
class A {
public:
A();
~A();
};
class B
{
public:
B();
~B();
};
A::A() { cerr << "Construction of A" << endl; }
A::~A() { cerr << "Destruction of A" << endl; }
B::B() { cerr << "Construction of B" << endl; }
B::~B() { cerr << "Destruction of B" << endl; }
int main()
{
ra->rb = rb;
rb->ra = ra;
}
-
In the general case the pointer returned by
new
can be used to build only one Ref. If it is used to build several Ref, the object will be destroyed several times and the program will crash. See RCObject
to avoid this problem.
Definition at line 77 of file rcptr.h.