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.
Actually the caller gets the reference (which is a pointer from
low-level POV), but allocates on stack struct object, and then
does copy from returned reference to that stack object.
> 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.
Yes, that the point - D does not have references like C++. And I
should thought about C++ influence on understanding D :)
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