gauteh
gauteh

Reputation: 17215

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()?

Upvotes: 0

Views: 972

Answers (2)

Tristan Brindle
Tristan Brindle

Reputation: 16864

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).

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249652

Yes, you probably should. It would be cleanest to also create the mime_object in the constructor rather than taking a raw pointer in from outside. If you take a raw pointer from outside it may be a bit unclear who owns the object and is responsible for releasing it.

Also note that you will need to override or disable the copy constructor, else you will have a double-unref situation if B is copied.

Upvotes: 0

Related Questions