D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 10625 - Compiler should warn or disallow using slice syntax in initialization
Summary: Compiler should warn or disallow using slice syntax in initialization
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords: accepts-invalid
Depends on:
Blocks:
 
Reported: 2013-07-12 09:57 UTC by Andrej Mitrovic
Modified: 2022-07-04 17:38 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Andrej Mitrovic 2013-07-12 09:57:21 UTC
-----
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 bearophile_hugs 2013-07-12 10:33:05 UTC
Related to Issue 7445 ?
Comment 2 Vladimir Panteleev 2015-05-19 00:18:11 UTC
Slice copies now require [] on both sides (arr1[] = arr2[]) so I'm not sure how relevant this is now.
Comment 3 Andrej Mitrovic 2022-07-04 17:38:14 UTC
(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~