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

Reply via email to