Jonh Wendell píše v Út 27. 04. 2010 v 10:46 -0300:
Hi, folks. I wrote a simple singleton: 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. [...] It refs the result variable before return. So, there's always a valid object outside... How to handle that? Thanks,
From you description I don't quite understand what you want it to do,
but I'll assume you want the object freed when all external references
are destroyed. In that case, modify your code like this:
public class Prefs {
private unowned static Prefs instance; // unowned so as not to increase ref count
public static Prefs default() {
if (instance == null) {
var newobject = new Prefs(); // you need a strong reference here
instance = newobject;
return newobject; // reference is passed to the caller
} else {
return instance; // this just refs the instance and passes reference to the caller
}
}
private Prefs () {
stdout.printf ("constructor\n");
}
~Prefs () {
stdout.printf ("destruction\n");
instance = null; // unowned doesn't know it's content's lifespan, so you have to clear it manually
}
}
Hope I didn't make any mistakes here and that this is what you mean. :)
Note though that this is NOT thread safe. If you access these from
multiple threads, you'd need something much more elaborate.
Attachment:
signature.asc
Description: Toto je digitálně podepsaná část zprávy