Static Array Idiom not working anymore.

Steven Schveighoffer schveiguy at yahoo.com
Tue Jun 12 14:44:12 UTC 2018


On 6/12/18 10:35 AM, 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

auto myStaticArray = [1,2,3].s;

Now use it anywhere you need dynamic arrays as myStaticArray[]. A lot of 
times, it will work without having to slice it.

What you are being told is that your memory is not being kept around. 
Essentially what you had originally was a memory corruption bug (yes, 
even before the deprecation happened). Don't do that anymore!

Note to ponce, please update your idioms, this is NOT safe, even within 
the same function. Just because it does work, doesn't mean it will 
always work. The language makes no guarantees once the lifetime is over.

-Steve


More information about the Digitalmars-d-learn mailing list