On Thursday, 24 January 2013 at 17:35:58 UTC, Ali Çehreli wrote:
On 01/24/2013 09:26 AM, ParticlePeter wrote:
> 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 Maxim Fomin noted, I didn't word it correctly: The caller
does get a reference to the returned object.
So, the sole purpose is not to pass a variable to a ref-taking
function.
> 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 ?
Not true. There are no local ref variables nor ref member
variables in D. All you need to do is to use pointers instead:
ref int foo()
{
return *new int;
}
struct S
{
int i;
int * j;
this(int i)
{
this.i = i;
this.j = &foo(); // member pointer
}
}
void main()
{
int* i = &foo(); // local pointer
}
No, the pointer syntax is not the cleanest. :)
Ali
This is what I meant :-) I can't return a reference ( with
reference I don't mean reference type, but semantically a
reference ) to a class member, but I can return the address of
this member, which, to my understanding is an implicit pointer.
struct Foo {
int val = 3 ;
auto getValPtr() { return & val ; }
}
Foo foo ;
writeln( foo.val ) ; // = 3
auto valPtr = foo.getValPtr() ;
* valPtr = 7 ;
writeln( foo.val ) ; // = 7