Singleton Pattern with struct

ParticlePeter ParticlePeter at gmx.de
Thu Jan 24 09:26:20 PST 2013


On Thursday, 24 January 2013 at 17:00:44 UTC, Ali Çehreli wrote:
> On 01/24/2013 08:52 AM, ParticlePeter wrote:
>
> > This method here ( my first approach ) does return a
> reference to an
> > object on the heap, right ?
>
> Yes, but the caller does not get a reference.
>
> > static ref Singleton instance() {
> > if ( s is null )
> > s = new Singleton( 0 ) ;
> > return * s ;
> > }
> >
> > so when I use it with:
> > auto another_s = Singleton.instance ;
> >
> > Why is the s inside the struct and another_s not identical ?
> > Afaik that is the purpose of the ref keyword ?
>
> When you print the type of another_s you will see that it is 
> not a ref, because unlike C++, D does not have local ref 
> variables; it has pointers for that purpose.
>
> import std.stdio;
>
> ref int foo()
> {
>     return *new int;
> }
>
> void main()
> {
>     auto i = foo();
>     writeln(typeid(i));
> }
>
> Prints 'int', not 'ref int'. So, i is a copy of the dynamically 
> created int.
>
> Ali

Thanks, I re-read the purpose of ref type function() in the D 
programming language, and the sole purpose is that such a 
function call can be directly a parameter to another function 
expecting a ref ? As:

ref int foo()  {  return some class member ;  }
void bar( ref int data )  {  do something with data ;  }

This means, it is never ever possible to initialize any variable 
with a reference some class/struct member data ? Unless I return 
the address of the member data ?




More information about the Digitalmars-d-learn mailing list