Singleton Pattern with struct
Maxim Fomin
maxim at maxim-fomin.ru
Thu Jan 24 08:07:35 PST 2013
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.
More information about the Digitalmars-d-learn
mailing list