GNOME Bugzilla – Bug 567076
return value behaviour of gobject constructor is questionable/not defined
Last modified: 2013-05-09 15:38:46 UTC
Lets look at this gobject constructor: static GObject* my_xxx_constructor(GType type, guint n_construct_params, GObjectConstructParam *construct_params) { MyXxx *self=MY_XX(G_OBJECT_CLASS (parent_class)->constructor (type, n_construct_params, construct_params)); if(!self) return(NULL); if(!my_do_construct_init(self)) { // failed goto Error; } return(G_OBJECT(self)); Error: g_object_unref(self); return(NULL); } Questions 1: Am I allowed to return NULL? I looked at g_object_newv() and it would do plenty calls with object=NULL. Smells bad. Is is a bug or if not allowed, shouldn't it be documented. Also if its not allowed, how do I handle failure in the constructor? Question 2: If its allowed, is the g_object_unref(self) okay at that point (for a not fully created object)?
You are not allowed to return NULL from g_object_new, as far as I know.
For things that can fail, a good pattern is to split it off into a separate foo_object_start method or the like, which can then also take a GError. It's unfortunate that gobject constructors can't throw, but it's just the way things are as I understand it.
Seems you are right. A _start method sounds not that good as it would be class specific. What basically happens is that I deserialize objects from files and use g_try_new when allocating memory based on the files. I'll think of some convention for my objects. But it would still be good to make this more explicit in the docs. I saw several comments in e.g. gio that shows that people are not sure about it.
Its clearly not fixable in the current stable API.
I think the intention these days is that g_object_new() cannot fail, but objects with failable constructors should implement GInitable. Is there anything else to do here?
GInitable sound good. Closing this ticket.