'return this' allows binding rvalues to references
Steven Schveighoffer
schveiguy at yahoo.com
Mon Apr 8 11:18:28 PDT 2013
On Mon, 08 Apr 2013 13:58:17 -0400, Ali Çehreli <acehreli at yahoo.com> wrote:
> 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());
> }
It has been brought up before.
Essentially, the compiler turns a blind eye when passing rvalues by
reference if binding to this. It's kind of unavoidable, to prevent it
would be a major pain point, since simple accessors should easily be able
to be called on rvalues, and you can't remove the 'ref' of 'this'.
I recall in the past, Andrei wishes to remove that possibility (maybe I'm
wrong), but I think it would be too impractical.
-Steve
More information about the Digitalmars-d
mailing list