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 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(); }
Attachment:
smime.p7s
Description: S/MIME cryptographic signature