Singleton Pattern with struct

Maxim Fomin maxim at maxim-fomin.ru
Thu Jan 24 06:43:17 PST 2013


On Thursday, 24 January 2013 at 14:11:10 UTC, ParticlePeter wrote:
> Hi,
>
> I am trying to figure out the singleton pattern with a struct 
> instead of a class:
> [code]
> struct Singleton  {
>
> private :
> 	this( int a = 0 ) {} ;
> 	static Singleton * s ;
>
> public :
> 	@disable this() ;
> 	static ref Singleton instance()  {
> 		if ( s is null )
> 			s = new Singleton( 0 ) ;
> 		return * s ;
> 	}
> 	
> 	int val = 0 ;
> }
> [/code]
>
> This compiles, but when I use it:
> [code]
> 	auto s = Singleton.instance ;
> 	writeln( s.val ) ;
>
> 	Singleton.instance.val = 2 ;
> 	writeln( s.val ) ;
> [/code]
>
> I get:
> 0
> 0
>
> Where is my mistake ?
>
> Cheers, PP !

Even if Singleton.instance returns by ref, s object is still 
stack-allocated struct, which is not affected by further 
modification of private pointer.

import core.stdc.stdio : printf;

struct Singleton  {

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

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

         int val = 0 ;
}

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

         Singleton.instance.val = 2 ;
         printf( "%d\n",  s.val ) ; // also 0
	printf( "%d\n", Singleton.instance.val); // is 2 as expected
}


More information about the Digitalmars-d-learn mailing list