Closed p0nce closed 2 years ago
Steve is right of course and provide a hint about what to replace in the article.
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
Another possibility is to use myStaticArray
instead of declaring myDynamicArray
, and just slice it where you need to. Static arrays are pretty close to the same as dynamic arrays except where you need to shrink/grow the array.
FYI, someone just posted a discord post saying how they learned this technique from your page. It really should be changed. I can do a PR.
Oh I had forgotten about this bad "trick". I always use static immutable arrays for that. Probably the idiom could leave the page indeed. It's not the only objectionnable code.
Thanks for PR!!!
Do you want the article gone from the internet? static immutable array works already
Well, it takes a lot of benefit out of it if you have to write it in 2 lines.
consider that the point is to make a nogc array literal. Using the now-standard staticArray
is probably best, without even making it a dynamic array:
auto justLikeDynamicArray = [1, 2, 3].staticArray;
It should work just as well as a dynamic array, and it also implicitly converts to dynamic arrays. But I'm not sure of the target audience.
I think also, using it to pass a dynamic array to a function is OK without having to save a copy, because that dynamic array shouldn't live past the statement (dip1000 will prevent you from passing this as a non-scope dynamic array).
So there are potential improvements. I just wanted to make sure the memory corruption didn't remain.
OK. Let me know if we shoud phase out "idiom" from this site, that shouldn't be followed. It was often written to explore the limits rather than responsible use.
https://forum.dlang.org/thread/crhnwahpcgmjbnqupzhi@forum.dlang.org
Presumably the compiler stopped warning about escaping references?