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

Jonathan M Davis jmdavisProg at gmx.com
Fri Jun 1 12:18:06 PDT 2012


On Friday, June 01, 2012 19:19:17 Sandeep Datta wrote:
> > 1. It's needed so that you can call it when calling C code.
> 
> Why can't we just use information from the C function signature
> to determine when an address needs to be passed? Why is manual
> intervention required here?

How about something like

int myVar;
cFunc(&myVar, 7);

The C function takes a pointer, and I want to pass a local variable to it. & 
is the way to do that. Even if I would have used ref or out for such a 
function if it were a D function, it's a C function, so I can't do that.

> > 2. Just because ref is often better than a pointer doesn't mean
> > that it's
> > never valuable to be able to pass a pointer to a variable.
> 
> Passing a pointer may be useful but IMO we should restrict such
> things to the unsafe context.

If you don't want to use them, don't use them. But pointers _are_ part of 
@safe because they _are_ safe. It's pointer arithmetic which isn't @safe. AA's 
in returns a pointer. If you want to put something other than a class on the 
heap, you need a pointer. Pointers aren't going anywhere. And if you need a 
pointer to something which isn't a pointer, then you need &.

> > 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.

> > 4. & is useful for getting function pointers.
> 
> What does the function name represent when not used with an
> ampersand? If it doesn't represent anything then I think the
> language can be changed to yield an address directly without an
> ampersand.

That wouldn't work due to properties.

Really, if you prefer to use ref over pointers, then use ref and don't use &. 
But & is useful and necessary for some circumstances and removing it would 
cripple us for little to no benefit.

- Jonathan M Davis


More information about the Digitalmars-d mailing list