auto ref is on the docket
kinke via Digitalmars-d
digitalmars-d at puremagic.com
Mon Jun 22 15:18:48 PDT 2015
On Monday, 22 June 2015 at 18:34:37 UTC, Namespace wrote:
> On Monday, 22 June 2015 at 18:03:43 UTC, Temtaime wrote:
>> I see no reasons why « ref in » is bad. Maybe someone explain ?
>> It's also natural for those who came from C++.
>> In C++ there's no problem with const&, so why they will be in
>> D?
>
> Because const is transitive in D and therefore more restrictive.
That's not a reason. It's just an additional restriction imposed
by D and only prevents you from using the proposed `in ref
T`/`const auto ref T` *shudder* equivalents if
const-transitiveness would be violated. In my day-to-day C++
work, I almost never have to do that.
C++ "simply" ;) relies on the callee not escaping rvalue
references bound to `const T&`. D's `(const/immutable) ref` only
allows lvalue arguments. It simply says: 'Hey stupid, don't give
me an rvalue reference, it might escape!' So to circumvent this
common problem, you'll currently have to either (a) create an
`auto ref` template or (b) declare a new variable, potentially
having to introduce a new scope.
Is it ugly?
(a) Leads to code bloat, but provides for in-place parameter
construction (and no indirections) for rvalue arguments of suited
types.
(b) Definitely ugly.
Is it safe now?
(a) Ideally, the rvalue argument was in-place constructed in the
function parameters stack. Noone but you, the dev, prevents the
callee from escaping a reference to the parameter though.
(b) Well, the code is more verbose and emphasizes the original
function argument expression. But it's obviously still all your
responsibility to take care of proper lifetime for escaping
references. Just declaring the variable right before the function
call isn't safer than passing the rvalue reference directly.
So none of this really solves the underlying problem. One
solution consists in classifying function parameter references as
non-escaping ones (proposed `scope ref`/non-template `auto ref`
accepting rvalues too, to be verified by compiler) and escaping
ones (`ref`), the bad ones to watch out for. I'd like having to
syntactically annotate an lvalue argument passed by non-scope
ref, analog to C#, i.e., `foo(ref argument)`, to more easily
catch the eye.
More information about the Digitalmars-d
mailing list