Is the address-of operator (&) really needed?

Artur Skawina art.08.09 at gmail.com
Fri Jun 1 13:18:19 PDT 2012


On 06/01/12 22:03, Jonathan M Davis wrote:
> On Friday, June 01, 2012 21:48:01 Artur Skawina wrote:
>> On 06/01/12 21:18, Jonathan M Davis wrote:
>>>>> 3. ref doesn't work with variadic templates very well. Take a
>>>>> look a
>>>>> std.getopt.getopt. It takes pointers, not refs, and there isn't
>>>>> a way to make
>>>>> it take refs.
>>>>
>>>> Is it because getopt() is a C function? If it is see my reply to
>>>> your point #1. I'll admit I do not know enough D to understand
>>>> what you are saying, some explanation will be helpful.
>>>
>>> It's not a C function. It's a variadic template. It's instantiated with
>>> whatever types it's given. It's literally _impossible_ to use ref with
>>> that
>>> sort of function. So, if you want it to take the variable and write to it,
>>> you have to pass a pointer to it.
>>
>> import std.stdio;
>>
>> void go(A...)(auto ref A a) {
>> a[0] = 42;
>> a[1].y--;
>> }
>>
>> struct S { int y; }
>>
>> void main() {
>> int x;
>> S s;
>>
>> go(x, s);
>>
>> writeln(x, " ", s);
>> }
> 
> auto ref is _completely_ different from ref. The compiler chooses whether to 
> pass by ref or not with the idea that it will pick whatever is most efficient 
> for that type, but it's implementation-dependent whether something will be 
> passed by ref or not. And using ref is no solution, because then _all_ of the 
> arguments must be lvalues. If you want a function to take an arbitrary set of 
> arguments where some of them are passed by ref and others not, you _can't do 
> it_. You have to use pointers instead, because the types of all of the 
> parameters are inferred from the arguments, and nothing ever gets inferred as 
> ref, because ref is not a type constructor.

I only used "auto ref" so that nobody would complain that it fails for non-lvalues.
You can use just 'ref', and i'd agree that such an interface would be saner.

However, if you know of a case where 'auto ref' behaves as you describe, file it as
a bug. That's not how it's defined, and that is not how it could be sanely implemented.
The sane definition is 'if it's an lvalue then it's a ref parameter'. And if you go
and check http://dlang.org/template.html you will see it's defined exactly like that.
Really, the compiler *cannot* decide by itself if something is passed by value or
not, it would make this feature unusable.

artur


More information about the Digitalmars-d mailing list