Re: [Vala] Singleton and reference count
- From: Mike Massonnet <mmassonnet gmail com>
- To: Jonh Wendell <jwendell gnome org>, vala-list gnome org
- Subject: Re: [Vala] Singleton and reference count
- Date: Tue, 27 Apr 2010 18:11:42 +0200
2010/4/27 Sam Wilson <tecywiz121 hotmail com>:
On Tue, 2010-04-27 at 10:46 -0300, Jonh Wendell wrote:
Hi, folks. I wrote a simple singleton:
public class Prefs {
private static Prefs instance;
public static Prefs default() {
if (instance == null)
instance = new Prefs ();
return instance;
}
public static unowned Preferences get_default () {
if (preferences == null) {
preferences = new Preferences ();
preferences.add_weak_pointer (&preferences);
}
else
preferences.ref ();
return preferences;
}
To invoke such an object inside a variable I do it like this with the
unowned keyword:
private unowned Xfmpc.Preferences preferences;
...
this.preferences = Xfmpc.Preferences.get_default ();
That is taken from xfmpc[0], the difference is that, for a singleton,
it makes the pointer “weak” so that it is effectively reset to nil
once the last count is removed. Also note the return type that
includes the keyword unowned, that is needed for Vala. Just run the
compiler as valac -C to have a look at the differences, that teaches
always a lot more.
Hopefully this will get you a little closer to what you are trying to
achieve, I can't confirm the destructor is called, but I guess it
should.
[0] http://git.xfce.org/apps/xfmpc/tree/src/preferences.vala
Regards
Mike
private Prefs () {
stdout.printf ("constructor\n");
}
~Prefs () {
stdout.printf ("destruction\n");
}
}
And in the other file, I do:
var prefs = Prefs.default ();
.... use prefs var...
The prefs var doesn't get destroyed, thus my destructor is never
called.
You probably want to make default return an "unowned Prefs" instead of
just "Prefs", that way the reference count is never increased. I might
be terribly wrong though, I am still not very fluid with vala's memory
management.
Sam
_______________________________________________
vala-list mailing list
vala-list gnome org
http://mail.gnome.org/mailman/listinfo/vala-list
--
Mike
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]