gobject.WeakNotify and dispose call

I’m using g_object_weak_ref() to be notified when an object is being disposed and free any weak reference to it. My question is: since the callback is called when the “dispose” method is executed, and since the “dispose” method can be called several times, can I receive the signal more than once and, then, I must call g_object_weak_unref() in the callback?

No, you have call g_object_weak_unref() every time you change the weak reference on a live object.

For instance:

static void
on_weak_unref (gpointer data,
               GObject *pointer)
{
  YourObject *self = data;

  self->foo = NULL;
}

void
your_object_add_foo (YourObject *self, FooObject *foo)
{
  g_return_if_fail (YOUR_IS_OBJECT (self));
  g_return_if_fail (foo == NULL || FOO_IS_OBJECT (foo));

  if (self->foo != foo)
    {
      if (self->foo != NULL)
        g_object_weak_unref (G_OBJECT (self->foo), on_weak_unref, self);

      self->foo = foo;

      if (self->foo != NULL)
        g_object_weak_ref (G_OBJECT (self->foo), on_weak_unref, self);
}

static void
your_object_dispose (GObject *gobject)
{
  YourObject *self = YOUR_OBJECT (gobject);

  if (self->foo != NULL)
    {
      g_object_weak_unref (G_OBJECT (self->foo), on_weak_unref, self);
      self->foo = NULL;
    }

  G_OBJECT_CLASS (your_object_parent_class)->dispose (gobject);
}

Inside the GWeakNotify callback the object has already gone, you only get a valid pointer that you can use to clean up your own state.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.