still confused about call by reference
Hoenir
mrmocool at gmx.de
Mon Oct 29 04:52:45 PDT 2007
Nathan Reed schrieb:
> Hoenir wrote:
>> I'm still a bit confused about call by reference. When do I have to
>> explicitly use the & operator and when to use in, out and inout?
>> I want to convert my C++ vector struct to D:
>>
>> struct vec3
>> {
>> vec3 operator+(const vec3& v) const
>> {return vec3(x+v.x, y+v.y, z+v.z);}
>> vec3 operator-(const vec3& v) const
>> {return vec3(x-v.x, y-v.y, z-v.z);}
>>
>> I'm also wondering about how to handle the constness.
>> Thanks in advance for any help :)
>
> In C++, const references are used to signal the data is not changed by
> the function, and is passed by reference purely for efficiency's sake. I
> believe the correct D equivalent is 'in'. The D spec states that 'in'
> is equivalent to 'final const scope', which means writing to the
> parameter is prevented, as in C++.
>
> The spec does not say whether 'in' results in pass-by-reference or not,
> but in this case, I believe that is a decision that should be made by
> the compiler, not the programmer.
>
> C++ non-const references are used to signal out-parameters, so the D
> equivalent would be out or inout, depending on whether your function
> wants to use the value that is passed in or not - 'out' parameters are
> initialized to their type's default value when the function begins, so
> any value that was there when the function was called gets clobbered,
> while 'inout' parameters let you read the original value.
>
> Honestly, I'm not entirely sure what D's 'ref' parameter-storage class
> is for, since AFAICT all the uses of pass-by-reference are covered by
> in, out, and inout.
>
> Thanks,
> Nathan Reed
I think I read somewhere, objects are automatically passed by reference
and if you add in or out it means the pointer rather than the data.
More information about the Digitalmars-d-learn
mailing list