Sam Wilson píše v Út 27. 04. 2010 v 18:39 -0400:
On Tue, 2010-04-27 at 19:42 +0200, Jiří Zárevúcky wrote: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.For everyone's reference, a singleton is an object that exists for the lifetime of an application, of which there is only one instance ever.
I think that's a matter of interpretation. Sometimes you may need an object which has at most one instance, not always exactly one. Whether you call it a singleton or not is a stupid discussion.
I propose the following code, it seems to work and it calls the destructor. The only questionable part is that vala doesn't unref namespace scoped variables when the program terminates, so you have to do that manually. public class Singleton<G> { public G instance {get; private set; } public Singleton(owned G instance) { _instance = (owned) instance; } } public class Prefs { internal Prefs () { stdout.printf ("constructor\n"); } public void do_something() { stdout.printf("Doing something...\n"); } ~Prefs () { stdout.printf ("destruction\n"); } } Singleton<Prefs> preferences; public static void main (string[] args) { preferences = new Singleton<Prefs>(new Prefs()); preferences.instance.do_something(); preferences.unref(); }
What's the point of this code? The Singleton class is redundant, you can do exactly the same just by storing a single instance of Prefs in a global variable. That's not a singleton. Note: you should use preferences = null, rather than unref()
Attachment:
signature.asc
Description: Toto je digitálně podepsaná část zprávy