Jive reference manual
|
Provides support for automatic garbage collection. More...
#include <jem/base/Collectable.h>
Protected Member Functions | |
Collectable () | |
Creates an empty Collectable . More... | |
~Collectable () | |
Frees resources. More... | |
Objects derived from the Collectable
class are subjected to automatic garbage collection. Thesecollectable objects are created on the heap and are automatically deleted when they can no longer be reached from the program. It is not possible to delete collectable objects explicitly through a delete expression.
Collectable objects are normally accessed through instances of the template class Ref
that mimics the behavior of a pointer. As long as a collectable object can be reached through a Ref
instance, or a sequence of Ref
instances, that object will not be deleted. Although one can also access collectable objects through normal pointers, it is unspecified whether the existence of a route from a live pointer (i.e. a pointer that can be reached from the program) to a collectable object prevents the deletion of that object. This means that one can not be sure that a collectable object exists when it can only be reached through one or more normal pointers. This is also true for references to collectable objects.
Collectable objects must be created with the template function newInstance()
that mimics a new expression but returns a Ref
object instead of a normal pointer. The newInstance()
function can be supplied a variable number of arguments that will be passed on to the matching constructor of the collectable class. If the constructor throws an exception, newInstance()
will deallocate all previously allocated memory and re-throw the exception, just like a new expression does. The following example shows how the newInstance
function can be used.
The function newInstance()
is not able to call a constructor that has one or more references (such as int&
) in its argument list. Normally this is not a problem because a constructor will only rarely need to modify its arguments. If, however, this is a problem for you, use a pointer instead of a reference.
A collectable object must not be created on the stack. To prevent this from accidentally happening, a collectable class should declare its destructor as a protected or private member.
Collectable
class is based on a thread-safe reference counting scheme that does not work properly when collectable objects are referencing each other. For instance, if object A has a Ref
to object B which has a Ref
to object A, then both objects will never be deleted, even if they are no longer reachable from the program.
|
protected |
Creates an empty Collectable
.
|
protected |
The destructor of a collectable object is called when the object is deleted. Since it is not specified when the object is deleted, one should not depend on the destructor to free critical system resources such as file descriptors.