On Thursday, 24 January 2013 at 15:50:34 UTC, ParticlePeter wrote:
Got it, thanks, I changed the instance method to:
[code]
        static Singleton * instance()  {
                if ( s is null )
                        s = new Singleton( 0 ) ;
                return s ;
        }
[\code]

and everything works as expected.

Cheers, PP !

Yes, but this can be broken by:

import core.stdc.stdio : printf;

struct Singleton  {

private :
        this( int a = 0 ) {} ;
        static Singleton * s ;

public :
        @disable this() ;
        static Singleton* instance()  {
                if ( s is null )
                        s = new Singleton(0) ;
                return s ;
        }

        int val = 0 ;
}

void main()
{
        Singleton s = * Singleton.instance;
        printf( "%d\n", s.val ) ; //
        Singleton.instance.val = 2 ;
        printf( "%d\n", s.val ) ; //0
}

Here s is explicitly defined to be a struct object, not pointer (reference), so main.s is independent of further modification of Singleton.instance.

Reply via email to