Bug 10625 – Compiler should warn or disallow using slice syntax in initialization
Status
RESOLVED
Resolution
INVALID
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-07-12T09:57:21Z
Last change time
2022-07-04T17:38:14Z
Keywords
accepts-invalid
Assigned to
No Owner
Creator
Andrej Mitrovic
Comments
Comment #0 by andrej.mitrovich — 2013-07-12T09:57:21Z
-----
void main()
{
int[] source = [0, 1];
int[] arr1 = new int[](2);
arr1[] = source[];
assert(arr1 !is source); // ok
int[] arr2 = source[]; // looks like a copy
assert(arr2 !is arr2); // assert fails: but in fact it's not!
}
-----
The 'int[] arr2 = source[];' syntax appears as though the source contents are copied into arr2, but in fact this is the same code as 'int[] arr2 = source;'.
Since [] has a very special meaning, the above should either:
1) Become an actual deep copy, meaning arr2 would have to allocate space first and then copy contents. This would be a breaking and negative change due to performance implications.
2) Not compile. It looks like a deep copy but it isn't, and this can cause issues down the road (for example using memcpy or even OpenGL functions can create hard to track problems due to using the source and target arrays which point to the same memory).
I'd vote heavily towards 2.
Of course one can always use 'int[] arr2 = source.dup'.
Comment #1 by bearophile_hugs — 2013-07-12T10:33:05Z
Related to Issue 7445 ?
Comment #2 by dlang-bugzilla — 2015-05-19T00:18:11Z
Slice copies now require [] on both sides (arr1[] = arr2[]) so I'm not sure how relevant this is now.
Comment #3 by andrej.mitrovich — 2022-07-04T17:38:14Z
(In reply to Vladimir Panteleev from comment #2)
> Slice copies now require [] on both sides (arr1[] = arr2[]) so I'm not sure
> how relevant this is now.
Oh yeah this is definitely an invalid issue. Thanks~