Static Array Idiom not working anymore.

Steven Schveighoffer schveiguy at yahoo.com
Tue Jun 12 15:39:10 UTC 2018


On 6/12/18 10:54 AM, Seb wrote:
> On Tuesday, 12 June 2018 at 14:35:33 UTC, SrMordred wrote:
>> this idiom for creating static array used to work, but they are 
>> failing now.
>> What changed and whats the alternative?
>>
>> (from 
>> https://p0nce.github.io/d-idioms/#@nogc-Array-Literals:-Breaking-the-Limits) 
>>
>>
>> T[n] s(T, size_t n)(auto ref T[n] array) pure nothrow @nogc @safe
>> {
>>     return array;
>> }
>>
>> void main() @nogc
>> {
>>     int[] myDynamicArray = [1, 2, 3].s; // Slice that static array 
>> which is on stack
>> }
>>
>> //output:
>> Deprecation: slice of static array temporary returned by s([1, 2, 3]) 
>> assigned to longer lived variable myDynamicArray
> 
> FYI: There's a Phobos PR for such an idiom
> 
> https://github.com/dlang/phobos/pull/6489

Note, this only will add the 's' function (named staticArray) to phobos, 
it still does not allow you to implicitly slice the temporary on return.

In other words, even with this change, you STILL need to do:

auto myStaticArray = [1,2,3].staticArray;
auto myDynamicArray = myStaticArray[];

To not have memory corruption (and avoid the deprecation message).

-Steve


More information about the Digitalmars-d-learn mailing list