*in* vs *const ref*
Jonathan M Davis
jmdavisProg at gmx.com
Tue Nov 6 15:18:53 PST 2012
On Tuesday, November 06, 2012 22:52:53 Dan wrote:
> Later on another response is: "A huge difference between *in* and
> *const ref* which you don't cover at all is the fact that *const
> ref* must take an lvalue, whereas *in* doesn't have to"
>
> Why is this benefit huge? Is it just the convenience of being
> able to pass in literals or is it something more?
The difference between in and const ref, in is the same as const scope, and
const ref is well, const ref. So, in doesn't do anything with ref and thus
will copy most arguments to it (though copies do get elided in cases where the
compiler determines that it can do a move instead), whereas const ref won't
copy the variable, but it _will_ require an lvalue.
If a function requires an lvalue, then you have to pass a variable to it. Not
only does that mean that you can't pass literals to it, but you can't pass the
result of another function to it. For instance, if writefln required lvalues,
you couldn't do
writefln("%s(%s): stray message %s: %s", __FILE__, __LINE__, foo(), bar(7));
You'd have to do something like
string file = __FILE__;
size_t line = __LINE__;
auto f = foo();
auto b = bar(7);
writefln("%s(%s): stray message %s: %s", f, b);
That would be _really_ annoying. And the same goes for functions in general.
Functions which require lvalues are generally not user friendly unless you're
specifically looking to alter the variable passed in, in which case const ref
doesn't do what you want anyway.
> Also, it does not mention *in ref*, which I guess is same as
> *const ref* but with *scope*.
Yes. in is an alias for const scope, ad I would advise avoiding scope as much
as possible (so, I'd advise avoiding in as much as possible). The only time
that it works correctly right now is with delegates. In all other cases, it's
ignored, and once that's fixed, it'll break code all over the place. scope is
supposed to prevent the variable that you pass in from being escaped from that
function, which is sometimes useful (particularly with delegates) but is often
overly restrictive. And even if that's what you want, if it's not a delegate,
it doesn't get checked right now, so using scope or in gains you nothing
anyway. It's just better to avoid it.
> I wrote a small benchmark comparison and get the following
> results. If it is a bogus comparison for whatever reason let me
> know. It seems if performance is the only issue, just use *const
> ref* or *in ref*.
ref avoids a copy, so it will be faster in cases where the copy would be
expensive. That's why people use const& in C++ and why so many people are
annoyed with const ref in D requiring an lvalue. auto ref was supposed to
solve the problem, but it currently only works with templates. It's still
up in the air how this problem is going to be solved.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list