Is the address-of operator (&) really needed?
Jonathan M Davis
jmdavisProg at gmx.com
Fri Jun 1 14:42:32 PDT 2012
On Friday, June 01, 2012 22:18:19 Artur Skawina wrote:
> > 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.
As the feature was proposed, it was up to the compiler to decide whether
something was passed by lvalue or rvalue, it was supposed to choose whichever
was most efficient. If Walter made it more specific than that (as the docs would
indicate), then he's defined it more thoroughly, for better or worse.
But tt doesn't really matter. getopt can't be implemented using auto ref
regardless of how defined it is what's ref and not. It uses compile-time
reflection to examine the arguments and determine what they're for. Even
passing a flag as an lvalue would then make it a ref, making it look like it
was supposed to be taking an argument rather than being the string for the
flag. By taking pointers, it's explicit, and it works. That won't work with
ref. You'd have to be able to indicate _at the call site_ that something is
supposed to be passed by ref for it work, and the language doesn't have that.
D is a _systems language_. It's not going to get rid of the ability to take
the address of something. & is here to stay. If you want to use features that
don't involve pointers, then feel free to do so, but while D strives to make
the default safe so that you don't shoot yourself in the foot, it doesn't try
and make it so that you can't do anything dangerous which might cause you to
shoot yourself in the foot.
- Jonathan M Davis
More information about the Digitalmars-d