Bug 2509 – Compiler rejects inner function that return references

Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Linux
Creation time
2008-12-12T16:42:00Z
Last change time
2015-06-09T01:20:45Z
Keywords
rejects-valid
Assigned to
nobody
Creator
resume755

Comments

Comment #0 by resume755 — 2008-12-12T16:42:31Z
this code causes the error: void main() { int i; ref int func() { return i; } func() = 4; } lval.d(5): found 'ref' instead of statement lval.d(10): no identifier for declarator func lval.d(11): unrecognized declaration but code like this compiles: ref int func() { int* i = new int; return *i; } void main() { func() = 4; }
Comment #1 by 2korden — 2008-12-12T18:11:30Z
The following code doesn't work either: void main() { int i; int* func() { return &i; // Error: escaping reference to local variable i } } Replace a pointer with a reference and you get the same semantics and thus your code wont work, too. An errot message reminds me about escape analysis discussion past month and I think that this behaviour needs some additional elaboration from Walter because it never was announces nor documented. The analysis implemente, however, is not too smart as there are ways to trick it: void main() { int i; void func(ref int* p) { p = &i; // Okay, no complains here } } Other than this, looks like compiler isn't yet aware of inner functions that return references (it doesn't expect to find a 'ref' keyword at a function level). It makes the following valid code fail to compile: void main() { ref int func() { static int foo; return foo; } func = 4; }
Comment #2 by yebblies — 2011-06-06T21:28:24Z
*** This issue has been marked as a duplicate of issue 5959 ***