const ref parameters and r-value references
via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 2 03:24:49 PDT 2014
On Friday, 2 May 2014 at 08:17:09 UTC, Mark Isaacson wrote:
> I'm in the process of learning/practicing D and I noticed
> something that seems peculiar coming from a C++ background:
>
> If I compile and run:
>
> void fun(const ref int x) {
> //Stuff
> }
>
> unittest {
> fun(5); //Error! Does not compile
> }
>
> I get the specified error in my unit test. I understand that
> the cause is that I've attempted to bind ref to an r-value,
> what's curious is that in C++, the compiler realizes that this
> is a non-issue because of 'const' and just 'makes it work'. Is
> there a rationale behind why D does not do this? Is there a way
> to write 'fun' such that it avoids copies but still pledges
> const-correctness while also allowing r-values to be passed in?
There is `auto ref`, but it only works for templates and is
somewhat different:
void fun()(auto ref const int x) {
// Stuff
}
unittest {
fun(5); // pass by value
int a = 5;
fun(a); // pass by ref
}
It generates two functions, with and without ref respectively.
Allowing rvalues to bind to ref (not only const) has been
discussed on several occasions, but I don't remember the outcome.
Here is one discussion:
http://forum.dlang.org/thread/ntsyfhesnywfxvzbemwc@forum.dlang.org
More information about the Digitalmars-d-learn
mailing list