Search code examples
c++glibgobject

g_object_unref() member pointer of C++ Glib::Object sub-class in destructor?


If I have C++ class derived from Glib::Object with a pointer to a g_object (C-interface) from GMime:

 /* schematic set up of class */
 class B : public Glib::Object {
  public:
    GMimeObject * mime_object;
 };

the mime_object is created and then passed to class B upon instantiation. It is not g_object_unref()'ed. Should I g_object_unref() it in the destructor class B::~B()?


Solution

  • Yes, you need to unref it in the destructor. You may also need to call g_object_ref_sink() in the constructor to get refcounting exactly right.

    GObjects which inherit from GInitiallyUnowned (rather than directly from the base GObject) start off with a "floating" reference which must be "sunk". This is the case for all GTK widgets for example. I don't know offhand whether this applies to GMimeObject or not, but the documentation will tell you (or you can call g_object_is_floating() at runtime to find out if you need to sink it).