Re: GObject question.



On Thu, Jun 07, 2007 at 04:43:33PM -0300, Alexandre Moreira wrote:
> I don't know if this is the right place to ask, ...

Yes, it is.

> I am writing a class and would like to know if there is anyway that I
> can prevent the object from being created (or deleting it right after
> it, if the first alternative is impossible) when I find out problems
> in the constructor.
> 
> The thing is: my class only makes sense when it is related with a
> file. Let's say it's called XFileBuffer (X_FILE_BUFFER)
> 
> when a user asks for new object, like in
> 
> g_object_new(X_TYPE_FILE_BUFFER, "file-name", "myfile.txt", NULL);
> 
> I want to be able to check if "file-name" property is set to a file
> that can be read and read it to an internal buffer of my object, but I
> don't want it to be created when the file isn't available for some
> reason.
> 
> Is it possible that I check the reasonable conditions inside my
> constructor and return NULL on the g_object_new() call the user made
> if they're not met ?

It is not possible.  You can almost manage it by overriding
constructor() method and returning NULL, however, this leads
to various subtle problems, not last of them being
a segfault when you pass other properties than explicite
construction properties to g_object_new() (and similar
functions).

I can't speak for the developers, but IMO this just isn't
the intended use.

> If, so, what would be the best way of doing it (so that derived types,
> for instance, would automatically inherit such behavior).

Any object wrapping resources that can get into `failed'
state needs some means to represent this state, or states.
In some languages you can throw exceptions on failures, but
throwing an exception does not make the failed object
immediately disappear, so while exceptions can simplify the
coding, objects in a falied state can still exist and live
for a relatively long time.

Thus, the natural approach is to create the objects already
in failed state if the underlying resource is so unusable
that even its initialization fails.  As a big bonus you get
something (i.e. the object) to *query* about the type and
reasons of the failure.

> I believe what I am trying to make is *almost* like throwing an
> exception in a C++ constructor (although I don't know much C++)... and
> would like to know if GObject allows me to do anything like that.

The mechanism described above is probably as close as you
can get to exceptions for GObject construction.

Yeti

--
http://gwyddion.net/



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]