does 'auto ref T' copy or not if passed rvalue

Jonathan M Davis jmdavisProg at gmx.com
Mon Dec 17 13:04:49 PST 2012


On Monday, December 17, 2012 06:21:38 PM Dan wrote:
> For the code below, S is never copied even though a version of
> the function resolving to void x.foo!(x.S).foo(x.S) is called.
> How is this possible?
> Is it an optimization? I figure if I call a function that takes
> its parameter by value, there should be a copy.
> 
> Thanks
> Dan
> 
> --------------- Output -----------------
> T: abc is ref
> T: xyz is not ref
> --------------- Code -----------------
> import std.stdio;
> 
> struct S {
> char c[];
> this(this) {writeln("Copying S\n");}
> }
> 
> void foo(T)(auto ref T t) {
> writeln("T: ", t.c, (__traits(isRef, t) ? " is ref " : " is not
> ref "));
> }
> 
> void main() {
> S s = { ['a','b','c'] };
> foo(s);
> foo(S(['x', 'y', 'z']));
> }
> --------------
> 
> nm -C x | ddmangle | grep foo
> 0000000000477ab4 W void x.foo!(x.S).foo(ref x.S)
> 00000000004783fc W void x.foo!(x.S).foo(x.S)

struct literals are currently incorrectly considered to be lvalues (I think 
that that may finally be fixed on master though), so the lvalue version will be 
called for them right now. Once that's fixed, I don't know for sure, but what 
it will probably do is call the rvalue version but do a move, so no copy will 
be made.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list