Goal: provide a flexible model based on reference counting which can be integrated in applications which use or require different memory management models (such as garbage collection, aso...)
- RC(reference count)
- gobject_new ==> RC=1;
- gobject_ref ==> RC++;
- gobject_unref==>RC--;
- if(RC == 0){
- class->dispose();
- class->finalize();
- g_type_free_instance(); ==> object's instance memory will be freed or returned to
- the object pool for this type, depending on the memory allocation policy decided when the type was registered
- (through one of the g_type_register_* functions)
- if(is_the_last_instance){
- the type's class will be destroyed
- }
- }
Weak References: used to monitor object finalization:
g_object_weak_ref
adds a monitoring callback which does not hold a reference to the
object but which is invoked when the object runs its dispose method.
As such, each weak ref can be invoked more than once upon object
finalization (since dispose can run more than once during object
finalization).
g_object_weak_unref
can be used to remove a monitoring callback from the object.
Destruction process is split in two phases:
dispose
release all references to other member objects.
Finalize
complete the object's destruction process
(object methods should be able to run without program error(that is, without segfault :) in-between the two phases.)
the dispose handler can be invoked multiple times:
e.g.
a reference count cycle: object A references B which itself references object A.
invoke g_object_dispose
on
one of the objects.
If object A releases all its references to all objects, this means it releases its reference to object B.
If object B was not owned by anyone else, this is its last reference count which means this last unref runs B's dispose handler which, in turn, releases B's reference on object A.
If this is A's last reference count, this last unref runs A's dispose handler which is running for the second time before A's finalize handler is invoked !