References
Namespace
rswhite4 at googlemail.com
Fri Sep 20 02:44:50 PDT 2013
On Friday, 20 September 2013 at 09:36:18 UTC, andrea9940 wrote:
> Running this code I would expect to get "ref" three times, but
> ...
>
> -------
> import std.stdio;
> struct A {
> int[128] data;
> ref A opAdd(const ref A a) {
> A cp = this;
> cp.data[] += a.data[];
> return cp;
> }
> }
>
> void fun(A a) { writeln("copy"); }
> void fun(const ref A a) { writeln("ref"); }
>
> void main() {
> A a, b;
> fun(a + b); //prints "copy"
> fun(A()); //prints "copy"
> fun(a); //prints "copy"
This prints 'ref' if you change func(A a) to func(const A a) the
match of const ref isn't prefered over A a because const need an
implicit conversion.
> }
> -------
>
> After some tests I concluded that is not possible to pass the
> result of a+b as a reference (which is what interests me most)
> and this creates an evident performance problem.
> Is there any solution that I missed ?
a + b is an rvalue and will moved to func(A a). This is even
faster than ref. ;)
A() is also moved.
If you have two functions, one with const A a and one with ref
const A a, the latter accepts lvalues which are passed by ref and
the first accepts rvalues which are moved. So no performance
problem. ;)
If you're function is a template you can use 'auto ref' which
automatically generate two versions of your function: one with
and one without ref.
More information about the Digitalmars-d-learn
mailing list