meaning of "auto ref const"?

Basile B. via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 18 06:25:04 PST 2016


On Sunday, 18 December 2016 at 13:14:08 UTC, Picaud Vincent wrote:
> Reading std/bigint.d code:
>
> https://github.com/dlang/phobos/blob/00c1cc3b0d354363793c8b419ce84da722578138/std/bigint.d#L589
>
> I have seen this:
>
> bool opEquals()(auto ref const BigInt y) const pure @nogc
> {
>    return sign == y.sign && y.data == data;
> }
>
> my problem is that I do not understand the role/meaning of 
> "auto" in this context.


With auto ref, the parameter can be either a LValue or a RValue.
When passing a struct as auto ref, it's taken as ref.
for example:

struct Foo{this(this){writeln("copy");}}
struct Bar{@disable this(this);}
void testAsRef(T)(ref T t){}
void testAsValue(T)(T t){}
void testRefOrValue(T)(auto ref T t){}

Foo foo;
Bar bar;

testAsRef(1); // error 1 is not ref
testAsRef(foo); // ok, not copied
testAsRef(bar); // ok, not copied

testAsValue(1); // ok
testAsValue(foo); // ok but copied
testAsValue(bar); // error, could only be copied but postblit is 
disabled

testRefOrValue(1); // ok, not taken as ref
testRefOrValue(foo); // ok, not copied
testRefOrValue(bar); // ok, taken as ref

As you can see, auto ref is more flexible with the parameter. 
This make sense for templated functions.


More information about the Digitalmars-d-learn mailing list