On Sunday, 23 October 2016 at 06:36:21 UTC, Jonathan M Davis wrote:
You can mark a parameter as ref, and you get something similar to C++'s &, except that it only works on parameters, return types, and the variable for the current element in a foreach loop (you can't declare local variables that are ref), and ref parameters only ever accept lvalues, even if they're const. e.g.

void foo(ref int i) {...}

ref int bar() { return _i; }

foreach(i, ref e; arr) {...}

I think that most D code just passes structs around without worrying about the cost of copying unless the struct is particularly large or profiling has shown that copying it is too expensive. For a lot of stuff, it simply isn't a problem. And when it is, there's ref, or the struct can be put on the heap and passed around by pointer. But because we don't have an equivalent for const& that accepts rvalues, using ref simply to avoid copying can get annoying. So, it doesn't make much sense to do it unless it's actually necessary (whereas a lot of C++ code does it just in case it matters).

There is talk of possibly adding a way to pass rvalues by ref in D, in which case, you would get something similar to C++ const&, but there are problems caused by C++'s approach that we don't want in D, and D's const is enough more restrictive than C++ const that whatever we do can't be tied to const.

- Jonathan M Davis

There is still the way to use an universal rvalue => lvalue conversion function.

Reply via email to