g_autoptr()

(by request of Lars): “This is a public service announcement.”

For some time, GCC has had support for __attribute__((cleanup)) which is a really nice way for automatically cleaning up variables when they go out of scope.

After a few attempts at people suggesting it for GLib, Alex finally convinced me to give it another thought. We originally resisted calls to implement it on the basis of portability, but having it in libgsystem (which has provided wrappers for a while) has shown it to be extremely useful and very popular. I came up with a pretty nice basic API concept and we iterated on it during the Developer Experience Hackfest that Collabora just hosted in Cambridge.

The changes just landed in GLib.

These macros only work with GCC and clang, which means that you should not use them on programs that you want to be buildable by MSVC (or other compilers).

The new API is best explained with an example:

{
  g_autoptr(GObject) object;
  g_autoptr(gchar) tmp;
  g_auto(GQueue) queue;

  g_queue_init (&queue);
  object = g_object_new (...);
  tmp = g_strdup_printf (...);

  // no free required
}

In order to support this for your types, you need to make use of the G_DEFINE_AUTOPTR_CLEANUP_FUNC and related macros. This will happen automatically if you make use of the new G_DECLARE_DERIVABLE_TYPE or G_DECLARE_FINAL_TYPE macros.

Please use responsibly.