Bug 2486 – taking address of slice rvalue should not be allowed
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2008-12-02T13:03:00Z
Last change time
2015-06-09T05:11:38Z
Keywords
accepts-invalid, pull
Assigned to
nobody
Creator
kamm-removethis
Comments
Comment #0 by kamm-removethis — 2008-12-02T13:03:24Z
I was surprised to see that following compiles and generates reasonable code:
int[] a = [1, 2, 3]
auto addr = &a[0..2];
Since the frontend seems to explicitly allow it, it's probably intentional and we've made LDC behave the same way. Could a description and rationale be added to the spec?
Comment #1 by k.hara.pg — 2011-11-10T03:09:27Z
This is still valid in D2.
import std.stdio;
void main()
{
int[] arr = [1,2,3];
auto p = &(arr[0..2]); // same as &(arr[0..2])
writeln(typeof(p).stringof); // int[]*
writeln(arr.ptr);
writeln(&arr);
writeln(p);
assert(&arr == p);
}
I think this is bad behavior, because it allows nonsense code like follows.
void main()
{
int[] arr = [1,2,3];
foo(arr[0..2]); // ref parameter can receive lvalue made by slicing
assert(arr == [1,2,3]); // assertion succeeds...
}
void foo(ref int[] arr)
{
arr = [4,5,6]; // what is modified?
}
Comment #2 by bugzilla — 2012-01-22T20:13:33Z
I agree, and will fix the spec. So it's a compiler bug that this code is accepted. It should only work for const references. Changing to a compiler bug.
I found related bug that returning slice by auto ref causes an error.
----
struct S
{
int[] a;
auto ref opSlice(){ return a[]; } // line 4
}
void main()
{
S s;
s[];
}
Output:
----
test.d(4): Error: slice expression this.a[] is not a modifiable lvalue