You can also use this:
typeof(&g) f;
f = &g;
But I'd say it's definitely a bug if we can't declare delegates with
ref returns.
I think I get it now. The example is actually invalid code accepted by the dmd
frontend. It allows a pointer of type "int function() ref" to be implicitly
converted to "int function()". Internally the "int function() ref" returns a
pointer to an integer. Both integers and pointers are returned the
It's the same with GDC as is with DMD, just checked.
No I was wondering if a different compiler would treat the assignment of &g
to f as needing to generate a conversion from int* to int internally (which
I think is what Timon was expecting?), or if it would generate an error
because the signature of f does not match the signature of g (which is what
I'm using DMD 2.052. Why, are you allowed to declare delegates with ref returns?
Which compiler are you using? Have you tried a different one?
On Sat, Apr 9, 2011 at 10:55 AM, Andrej Mitrovic wrote:
> Interesting. The problem I think is that the delegate is declared as
> returning int, not ref int. I don't even think we can specify ref as
> the return value of a delegate. B
Interesting. The problem I think is that the delegate is declared as
returning int, not ref int. I don't even think we can specify ref as
the return value of a delegate. But if you try to declare the delegate
as returning an int*, you get this nice error:
Error: cannot implicitly convert expressio
It looks like in the absence of an assignment of the output of g() to some
value (say int b = g()) which the compiler would insert conversion code for,
the ref is retaining some pointer semantics. I'm guessing that because
writeln is variadic the compiler doesn't do anything with g's output (like
Whats the output of the following code supposed to be?
import std.stdio;
int a=0;
ref int g(){
writeln("called g");
return ++a;
}
void main(){
int function() f=&g;
writeln(cast(int)&a);
writeln(f());
writeln(f());
writeln(f());
}
The output using dmd 2.052
-144918776