转载请注明出处 blog.csdn.net/pingf0 或www.cnblogs.com/pingf
接上文
这一部分简要介绍下类的析构,或者成为终结。
还是多说几句,也算是对前文的补充
1.生成一个类是由父到子,析构的时候自然与之相对是由子到父。
2.GObject的内存管理并没有采用垃圾回收的方式【JAVA就采用此方式】,而是采用了引用计数的方式。
具体垃圾回收是怎么回事儿,本人还不清楚,所以就不提了。引用计数还了解一些,
但也不是此处的重点【哎,又写了点废话】。主要要补充的是如果要在一个对象中包含另一个对象,
需要在初始话时ref一下,析构的时候再将其unref.
3.GObject的析构其实分为两步,一步是dispose【曝光】,另一步是finalize【终结】。分别用来unref和free对象。
下面给出dispose和finalize的代码
Code
static void
jc_boy_dispose (GObject *gobject)
{
JcBoy *self = JC_BOY (gobject);
/*
* In dispose, you are supposed to free all types referenced from this
* object which might themselves hold a reference to self. Generally,
* the most simple solution is to unref all members on which you own a
* reference.
*/
/* dispose might be called multiple times, so we must guard against
* calling g_object_unref() on an invalid GObject.
*/
/////
/////
// if (self->priv->an_object)
// {
// g_object_unref (self->priv->an_object);
// self->priv->an_object = NULL;
// }
/* Chain up to the parent class */
G_OBJECT_CLASS (jc_boy_parent_class)->dispose (gobject);
}
static void
jc_boy_finalize(GObject *gobject)
{
JcBoy *self =JC_BOY (gobject);
g_free (self->priv->hobby);
g_free (self->priv->name);
g_print("boy finalized !\n");
/* Chain up to the parent class */
G_OBJECT_CLASS (jc_boy_parent_class)->finalize (gobject);
}
static void
jc_boy_dispose (GObject *gobject)
{
JcBoy *self = JC_BOY (gobject);
/*
* In dispose, you are supposed to free all types referenced from this
* object which might themselves hold a reference to self. Generally,
* the most simple solution is to unref all members on which you own a
* reference.
*/
/* dispose might be called multiple times, so we must guard against
* calling g_object_unref() on an invalid GObject.
*/
/////
/////
// if (self->priv->an_object)
// {
// g_object_unref (self->priv->an_object);
// self->priv->an_object = NULL;
// }
/* Chain up to the parent class */
G_OBJECT_CLASS (jc_boy_parent_class)->dispose (gobject);
}
static void
jc_boy_finalize(GObject *gobject)
{
JcBoy *self =JC_BOY (gobject);
g_free (self->priv->hobby);
g_free (self->priv->name);
g_print("boy finalized !\n");
/* Chain up to the parent class */
G_OBJECT_CLASS (jc_boy_parent_class)->finalize (gobject);
}
就这么简单【其实很麻烦吧。。。。XD】,但这些还不够,别忘了前面我们注册类用的是简化的G_DEFINE_TYPE,
而其实调用的是g_type_register_simple,这个函式里面里并没有注册次够用的函式,
所以在初始话时还要在显示声明下曝光和终结用的函式。
可以在class_init中声明
static void
jc_boy_class_init (JcBoyClass *klass)
{
……
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->dispose=jc_boy_dispose;
gobject_class->finalize=jc_boy_finalize;
……
}