'return this' allows binding rvalues to references

Ali Çehreli acehreli at yahoo.com
Mon Apr 8 10:58:17 PDT 2013


foo() below takes by-ref. Normally, rvalues cannot be passed to it:

struct S
{
     ref S memFunc()
     {
         return this;
     }
}

void foo(ref S s)
{}

void main()
{
     // As expected, fails to compile:
     // foo(S());

     // No problem: Just call a function that returns ref... :)
     foo(S().memFunc());
}

Obviously, it is the same problem for rvalues returned from functions:

     S bar()
     {
         return S();
     }

     foo(bar().memFunc());    // <-- compiles

This may be a trap especially in opAssign() because it is recommended to 
return by-ref unless there is a reason not to. (I wonder whether this is 
a reason not to. :) )

struct S
{
     ref S opAssign(S rhs)
     {
         return this;
     }
}

void foo(ref S s)
{}

void main()
{
     // As expected, fails to compile:
     // foo(S());

     // No problem; just assign... :)
     foo(S() = S());
}

Allowing assignment to rvalue feels like a bug there but I don't think 
we can prevent the programmer from doing S().memFunc() as in the first case.

Ali

P.S. I should have checked before writing this post. The following bugs 
seem related:

   http://d.puremagic.com/issues/show_bug.cgi?id=1596

   http://d.puremagic.com/issues/show_bug.cgi?id=3008

No, I haven't read them yet.


More information about the Digitalmars-d mailing list