temporary objects are not allowed to be pass by ref anymore
Mike Parker
aldacron at gmail.com
Sun Apr 19 08:23:21 PDT 2009
Denis Koroskin wrote:
> What's a rationale behind an issue described bug 2621?
> http://d.puremagic.com/issues/show_bug.cgi?id=2621
>
> Why isn't it allowed anymore?
>
> It broke quite a lot of my code. And while it is fixable by doing
>
> auto tmp = someFunctionThatRetunsStruct();
> someMethodThatAcceptsStructByReference(tmp);
>
> it looks ugly and unnecessary.
Yeah, I was recently caught by this when moving some code over to D2,
thinking I'd take advantage of some const refs. I was quite surprised
when my code wouldn't compile. Consider:
struct Foo
{
int x;
Foo opAdd(const ref Foo lhs)
{
Foo f = {x + lhs.x};
return f;
}
ref Foo opAddAssign(const ref Foo lhs)
{
x += lhs.x;
return f;
}
}
Given Foo a, b and c, the following fails to compile:
c += a + b;
The work around is to add an overridden opAddAssign that takes a non-ref
foo. Not pretty, especially when dealing with numerous methods. Rather
defeats the purpose of const ref parameters, does it not? And it's far
from intuitive, particularly when coming from C++.
More information about the Digitalmars-d
mailing list