Re: Abstract string properties with getter/setter functions



On Wed, 19 Sep 2007, Raffaele Sandrini wrote:

Hi there,

While implementing abstract properties in Vala we encountered a problem
regarding string properties with getter and setter functions:

public interface Test.MyIface {
	public abstract string text { get; }
}

A getter function of an abstract string property looks like:
char* test_my_iface_get_text (TestMyIface* self) {
       char* value;
       g_object_get (G_OBJECT (self), "text", &value, NULL);
       return value;
}

Property accessors in Vala always return weak references. This leads to
a memory leak in the calling function of the getter.

i'm not sure what you mean with weak/strong references when it
comes to strings. in C, pointers can be handed out which point to
0-terminated char arrays that represent strings. there's on reference
counting for strings in C as there is in C++. per convention,
for glib/gtk programs, some such string pointers must be g_free()-ed once.

callers of getters have to free the returned string in C.
for glib/gtk programs, if the caller doesn't need to free the string,
the return value should be G_CONST_RETURN gchar*.

We want property accessors to return weak references so just redefine
the accessors to return a strong reference is only a last-resort-option.

requesting that all string return types should be const char* is technically
not possible, because some strings need to be constructed in getters.

people who don't want to deal with these memory allocation issues (const
strings vs. caller-needs-to-free strings) should stay away from C, maybe
even C++, and use python, java, scheme, other-garbage-collected languages.

Since we do not see a way around this (yet) and we could not find an
example with strings in another project. I'm asking here if there is a
nice way around this.

i'm really not sure i understand your problem here...

BTW: There are equal issues with properties returning objects only there
you can add a hack into the getter unrefing the object before returning
it. This is not applicable with strings.

this is not applicable with objects. as soon as you called unref(obj),
the object will be destructed and gone, you can't hand it on any further,
"obj" will point to freed memory.
in some rare cases and if you're lucky, the object might stay around
a little longer because someone else could coincidentally hold another
reference. but this can't be relied upon.
a well formed getter implementation might do:
  return g_object_ref_sink (g_object_new (MY_TYPE_DATA_OBJECT, NULL));
once you g_object_unref() this return value, it'll be instantly vaporized with
a crushing noise (if you hooked up pulseaudio via destruction emission hooks ;)

cheers,
Raffaele

---
ciaoTJ



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