www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Confused about referencing in D

reply Gorge Jingale <Frifj mail.com> writes:
I'm pretty confused why the following code doesn't work as 
expected.

GetValue is a struct.

   auto value = GetValue();
   memcpy(&value, &val, Val.sizeof);

But if I plug in value direct to memset it works!!

   memcpy(&GetValue(), &val, Val.sizeof);

GetValue returns memory to stick a value in and the memcpy is 
copying it over. It is very confusing logic. Should I not expect 
the two cases two be identical?

I think that the assignment in the first case is not assigning 
the reference returned by auto ref GetValue().

I am expecting it to work like a pointer,

   void* value = &GetValue();
   memcpy(value, &val, Val.sizeof);

so to speak but it works more like

     S value;
     value = GetValue();
     memcpy(&value, &val, Val.sizeof);

which copies the data to the memory created for value and not the 
one returned by GetValue.
Jul 13 2016
next sibling parent rikki cattermole <rikki cattermole.co.nz> writes:
On 14/07/2016 6:23 PM, Gorge Jingale wrote:
 I'm pretty confused why the following code doesn't work as expected.

 GetValue is a struct.

   auto value = GetValue();
   memcpy(&value, &val, Val.sizeof);

 But if I plug in value direct to memset it works!!

   memcpy(&GetValue(), &val, Val.sizeof);

 GetValue returns memory to stick a value in and the memcpy is copying it
 over. It is very confusing logic. Should I not expect the two cases two
 be identical?

 I think that the assignment in the first case is not assigning the
 reference returned by auto ref GetValue().

 I am expecting it to work like a pointer,

   void* value = &GetValue();
   memcpy(value, &val, Val.sizeof);

 so to speak but it works more like

     S value;
     value = GetValue();
     memcpy(&value, &val, Val.sizeof);

 which copies the data to the memory created for value and not the one
 returned by GetValue.
Please provide the definitions of GetValue and Val.
Jul 13 2016
prev sibling next sibling parent kink <noone nowhere.com> writes:
On Thursday, 14 July 2016 at 06:23:15 UTC, Gorge Jingale wrote:
 I think that the assignment in the first case is not assigning 
 the reference returned by auto ref GetValue().
Yep. There's no such thing as C++ `auto& val = GetValue()` in D. You'd have to use a pointer instead: `auto pVal = &GetValue()`.
Jul 14 2016
prev sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Thursday, 14 July 2016 at 06:23:15 UTC, Gorge Jingale wrote:
 I think that the assignment in the first case is not assigning 
 the reference returned by auto ref GetValue().
`ref` in D is shallow, it only applies to the thing it is specifically on and is lost across assignments. Once you assign a ref to a new variable, it isn't ref anymore.
 I am expecting it to work like a pointer,
If you need a pointer, use a pointer! ref is a different thing.
Jul 14 2016