gobject reference count summary

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...)


  1. RC(reference count)
  2. gobject_new ==> RC=1;
  3. gobject_ref ==> RC++;
  4. gobject_unref==>RC--;
  5. if(RC == 0){
  6.         class->dispose();
  7.         class->finalize();
  8.         g_type_free_instance(); ==> object's instance memory will be freed or returned to
  9.                                                         the object pool for this type, depending on  the memory                                                                                                                                 allocation policy decided when the type was registered
  10.                                                         (through one of the g_type_register_* functions)
  11.         if(is_the_last_instance){
  12.                   the type's class will be destroyed
  13.         }
  14. }

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:

  1. dispose

    release all references to other member objects.

  2. 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 !

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章