GObject* instance1,* instance2; //指向实例的指针 GObjectClass* class1,* class2; //指向类的指针 instance1 = g_object_new (G_TYPE_OBJECT, NULL); instance2 = g_object_new (G_TYPE_OBJECT, NULL); g_print ("The address of instance1 is %p\n", instance1); g_print ("The address of instance2 is %p\n", instance2); class1 = G_OBJECT_GET_CLASS (instance1); class2 = G_OBJECT_GET_CLASS (instance2); g_print ("The address of the class of instance1 is %p\n", class1); g_print ("The address of the class of instance2 is %p\n", class2); g_object_unref (instance1); g_object_unref (instance2);
The address of instance1 is 0x55d3ddc05600 The address of instance2 is 0x55d3ddc05620 The address of the class of instance1 is 0x55d3ddc05370 The address of the class of instance2 is 0x55d3ddc05370
//file: example02.c #include<glib-object.h> staticvoidshow_ref_count(GObject* instance) { if (G_IS_OBJECT (instance)) /* Users should not use ref_count member in their program. */ /* This is only for demonstration. */ g_print ("Reference count is %d.\n", instance->ref_count); else g_print ("Instance is not GObject.\n"); } intmain(int argc, char **argv) { GObject* instance;
instance = g_object_new (G_TYPE_OBJECT, NULL); g_print ("Call g_object_new.\n"); show_ref_count (instance); g_object_ref (instance); g_print ("Call g_object_ref.\n"); show_ref_count (instance); g_object_unref (instance); g_print ("Call g_object_unref.\n"); show_ref_count (instance); g_object_unref (instance); g_print ("Call g_object_unref.\n"); g_print ("Now the reference count is zero and the instance is destroyed.\n"); g_print ("The instance memories are possibly returned to the system.\n"); g_print ("Therefore, the access to the same address may cause a segmentation error.\n");
return0; }
其中:
g_object_new创建一个实例变量,然后将变量的引用计数置为1
g_object_ref将其引用计数加1
g_object_unref将引用计数减1,如果此时引用计数为0,则析构变量。
输出:
1 2 3 4 5 6 7 8 9 10
Call g_object_new. Reference count is 1. Call g_object_ref. Reference count is 2. Call g_object_unref. Reference count is 1. Call g_object_unref. Now the reference count is zero and the instance is destroyed. The instance memories are possibly returned to the system. Therefore, the access to the same address may cause a segmentation error.