Re: [Vala] reference management.



Am Montag, den 19.03.2007, 17:18 -0300 schrieb Alexandre Moreira:
How exactly does reference management (g_object_ref || g_object_unref)
works in Vala ? I know it will unref everything I don't explicitly
tell it to ignore when returning methods (By the way, how do I tell it
to ignore anything ? I couldn't figure out the syntax)

Hi Alexandre,

Short answer: 

Reference counting happens automatically with vala.

Long answer (also will put this on live.gnome):

There are two kinds of references in vala: strong and weak references.
For strong references g_object_ref and -unref are invoked, if no other
functions are specified by CCode attributes. For weak references just
pointer assignment happens. Some special-casing is used for GList, so
you have to be carefully, which of your GList references are strong,
and which of them are weak, as otherwise you might frequently clone
your entire list by accident.

Currently all member variables are strongly referenced by default. To
make them weak add exactly this keyword. For local variables currently
some heuristics exist. Weak still is preferred, but there are some
thoughts to use always use strong references for local variables.
Problem with strong references on local variables: Whilst strong
references are quite cheap to maintain for GObject derived classes,
they can be extremely expensive for things like boxed types or GList.

Arguments for using strong references every where look like this:

        Foo x;

        if (bar) {
                Foo y = new Foo ();
                x = y;
        }

Citing Jürg: 

        Currently the compiler will define x as weak and y as strong
        reference at the end of the if block, y will be unrefed and x
        will have an invalid reference the only safe choice is to always
        use strong references.
        
While this problem still could be solved, by injecting some strong
shadow ref at the scope of x, things become more tricky for things like
this (also citing Jürg):
        
        Foo y = bar.x;  // x is e.g. field with strong reference
        bar.x = "foo";  // that will destroy the old value of bar.x

or:

        class Foo {
                public weak string foo_method() { 
                        return x;
                }

                public string x; // strong reference field 
        }

        Foo bar = new Foo();
        string x = bar.foo_method();
        bar.x = "bar";

At least the second case has no chance to be caught by the compiler and
is one of the reasons mark-and-sweep garbage collection can be much
faster then explicit memory management. On the other hand I wonder, if
the class Foo isn't fundamentally broken, by returning weak references
to non (semi) constant members.

This this is a good time to discuss reference counting in Vala.

Ciao,
Mathias




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