[Vala] A note about weak/unowned struct



Dear List,

Here is some of my observation regarding to weak/unowned struct, which I
would like to share with you.

I am not sure if the feature has landed or not, but currently a
weak/unowned struct is compiled into a bitwise copy of the memory
content of the referred struct. in other words, it is a readonly
'snapshot', although the name doesn't suggest this special feature at
all.

See the following program(compiled with 0.7.5)
------ Program ------
struct Struct {
        public int i;
        public Object o;
}
public void main() {
        Struct s = Struct();
        s.i = 100;
        s.o = new Object();
        unowned Struct ws = s;
        ws.i = 101;
        debug("s.i = %d", s.i);
        debug("ws.i = %d", ws.i);
        debug("s.o.ref_count = %u", s.o.ref_count);
        ws.o = null;
        debug("s.o.ref_count = %u", s.o.ref_count);
}

----- Program ends -----

It gives the result 

------ Result ----
** (process:11743): DEBUG: t.vala:11: s.i = 100
** (process:11743): DEBUG: t.vala:12: ws.i = 101
** (process:11743): DEBUG: t.vala:13: s.o.ref_count = 1
** (process:11743): DEBUG: t.vala:15: s.o.ref_count = 0

(process:11743): GLib-GObject-CRITICAL **: g_object_unref: assertion
`G_IS_OBJECT (object)' failed
------ Result ends -----

When ws.i changes s.i is left unaffected. When ws.o is set to null, the
object is unrefered. However, VALA still believe the strong reference
exists in s.o, which ultimately causes the 'critical' on s.o when s is
freed.

The rule of thumb is then never alter the content of a struct that you
don't own.


Yu




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