Storing a reference

Yuxuan Shui via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 1 13:38:13 PDT 2016


On Thursday, 1 September 2016 at 20:28:03 UTC, Rene Zwanenburg 
wrote:
> On Thursday, 1 September 2016 at 19:37:25 UTC, Yuxuan Shui 
> wrote:
>> [...]
>
> 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.

I think my approach is probably better, because I believe 
(correct me if I'm wrong): 1) it will never refer to a null 
object. 2) after DIP1000 is implemented we will be able to make 
sure there will be no dangling reference.


More information about the Digitalmars-d-learn mailing list