Storing a reference

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 1 14:07:36 PDT 2016


On 9/1/16 4:38 PM, Yuxuan Shui wrote:
> 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.

Referring to a null object is not a problem. Your program crashes 
ungracefully, but does not corrupt memory. However, in either approach, 
it can easily end up being a dangling pointer.

But to refer to a null location is quite easy:

int *foo; // null ptr
auto a = x(*foo);
assert(&a.xa() == null);

Your approach is less desirable because of the closure to point at a 
given reference which can be had with just a reference. Needless allocation.

-Steve


More information about the Digitalmars-d-learn mailing list