Bug 2521 – Not possible to return immutable value by ref

Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2008-12-17T07:40:00Z
Last change time
2015-06-09T01:20:50Z
Keywords
diagnostic, patch, rejects-valid
Assigned to
nobody
Creator
aarti

Comments

Comment #0 by aarti — 2008-12-17T07:40:59Z
module Test; immutable int val = 23; ref int func() { return val; } void main() { } ---- Result - compilation error: quicktest.d(3): Error: cast(int)23 is not an lvalue
Comment #1 by 2korden — 2008-12-17T17:29:52Z
Immutable variables are not lvalues, you can't take address of them because they might not present in a final executable. For example, everywhere you use val, it is replaced with 23. You can't return 23 by reference, can you? Besides, returning immutable values by mutable reference is disallowed: func() = 42; //what should this do if func() returns reference to immutable val?
Comment #2 by torhu — 2008-12-17T18:36:49Z
From the docs (Const and Invariant page): "Invariant declarations can appear as lvalues, i.e. they can have their address taken, and occupy storage." This one works: immutable(int)* func() { return &val; } I assume that this is supposed to work too: ref immutable(int) func() { return val; }
Comment #3 by aarti — 2008-12-18T02:26:45Z
comment to #1: I was not sure if this was supposed to work. But please notice that it is bug anyway as the line number in error message and message itself is totally misleading. It suggest that problem is with variable declaration, instead of with function.
Comment #4 by jason.james.house — 2008-12-22T19:35:59Z
This is definitely an invalid bug! Func has a return type of "ref int". The ref means that what gets returned by the function can be modified (and affect the underlying data used by func). If the return type of func was int, I would hope the code would compile, but that's a whole other issue...
Comment #5 by yebblies — 2011-06-07T04:22:52Z
This bug addresses two issues. This does not currently work: ------------------------------- immutable int val = 23; ref immutable(int) func() { return val; } Error: constant 23 is not an lvalue ------------------------------- And this gives the same terrible error message: ------------------------------- immutable int val = 23; ref int func() { return val; } Error: constant 23 is not an lvalue ------------------------------- The proposed fix (dmd pull 92) allows the first case, and changes the error to the following for the second case: Error: cast(int)val is not an lvalue The root cause of this bug is the fact that while running semantic on the return expression, the immutable variable's value is known at compile time, and is optimized without checking if the function returns an lvalue.
Comment #6 by k.hara.pg — 2011-06-17T02:59:16Z
*** Issue 2780 has been marked as a duplicate of this issue. ***
Comment #7 by bugzilla — 2011-06-30T13:23:06Z