Skip to content

glib/mem: Add g_clear_pointer_with() utility

Jonas Ådahl requested to merge jadahl/glib:wip/g-clear-pointer-with into master

Countless of times I've ended up having the following code pattern:

g_clear_object (&self->some_object);
g_clear_pointer (&self->data, g_free);
g_clear_pointer (&self->blob, blob_free);

if (self->borrowed_thing)
  {
    actual_owner_remove (self->actual_owner, self->borrowed_thing);
    self->borrowed_thing = NULL;
  }

if (self->borrowed_other_thing)
  {
    actual_owner_remove (self->actual_owner, self->borrowed_other_thing);
    self->borrowed_other_thing = NULL;
  }

Which is annoying beacuse in no way are the last 10 lines more relevant than the first three. This new utility function makes it possible to change the above to:

g_clear_object (&self->some_object);
g_clear_pointer (&self->data, g_free);
g_clear_pointer (&self->blob, blob_free);
g_clear_pointer_with (&self->borrowed_thing, self->actual_owner,
                      actual_owner_remove);
g_clear_pointer_with (&self->borrowed_other_thing, self->actual_owner,
                      actual_owner_remove);

Which makes it less of a punishment to deal with objects that needs to be removed from somewhere else instead of being just destroyed or freed.


Got annoyed by yet again have to write all the "if not null remove and set to null" boiler plate in a dispose function, so wrote this as a temporary relief. Any interesting in actually adding?

Edited by Jonas Ådahl

Merge request reports