Storing a reference

Rene Zwanenburg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 1 13:28:03 PDT 2016


On Thursday, 1 September 2016 at 19:37:25 UTC, Yuxuan Shui wrote:
> I just figured out how to store a reference:
>
> @safe:
> auto x(ref int a) {
> 	struct A {
> 		ref int xa() { return a; }
> 	}
> 	return A();
> }
> void main() {
> 	import std.stdio;
> 	int b = 10;
> 	auto a = x(b);
> 	a.xa = 20;
> 	writeln(b); //Prints 20
> }
>
> I have no idea if this is a right thing to do. Can someone tell 
> me if this is idiomatic D, and whether there're any catches to 
> this method or not?
>
> Thanks.

This will allocate a closure. A struct definition inside a 
function has a hidden context / closure pointer, unless it's a 
static struct.

There is nothing like a ref variable in D. If you want to refer 
to something someplace else, use a pointer. You can create a 
pointer wrapper which acts like a reference (untested):


auto toRef(ref T value)
{
   return Ref!T(&value);
}

struct Ref(T)
{
   private T* value;
   @property ref T _value() { return *value; }
   alias _value this;
}

Note that D's pointer syntax is a bit friendlier than C++'s: the 
dot operator works fine on pointers. A good reason to use the Ref 
wrapper is to forward arithmetic operations to the wrapped value.


More information about the Digitalmars-d-learn mailing list