Array literals are weird.
Blatnik
blatblatnik at gmail.com
Sat May 1 12:27:30 UTC 2021
On Saturday, 1 May 2021 at 11:50:27 UTC, Adam D. Ruppe wrote:
> There's several other options you can consider, including
> making foo take a static array
Yea this does work, but some functions really do need to take
many different array sizes. And in that case I guess you could
make the array size a template parameter. But this would lead to
template bloat for no reason in most cases.
> or an array variadic:
>
> foo(int[] a...)
This doesn't really work. It has the obvious problem of not being
able to pass 2 different arrays like this.
> or you can use the library `.staticArray` thing to expressly
> indicate your intention on the original foo
But this does work! I didn't know `std.array` had this. Thanks.
> but a good part of it too is to make the default thing be less
> likely to cause crash problems by accidentally escaping a
> reference to the stack.
You mean stuff like:
```D
int[] bug() {
return [1, 2, 3];
}
int[] a = bug();
a[0] = 42; // Works fine now, but use-after-free-ish if array
literals are static arrays.
```
Yea I can see how that would be a problem if array literals were
static arrays by default. But even right now the compiler is able
to catch this mistake pretty easily:
```D
int[] bug() {
int[3] a = [1, 2, 3];
return a; // Error: Returning `a` escapes a reference to a
local variable.
}
```
So the `.staticArray` thing is great but wouldn't it be even
better if we didn't have to import a library and type that in.
I still see no reason `[1, 2, 3]` should ever _not_ be considered
a `int[3]`, unless you explicitly ask for it:
```D
auto x = [1, 2, 3]; // This really shouldn't allocate anything.
auto y = [1, 2, 3].dup; // I explicitly asked for it, please
allocate!
```
More information about the Digitalmars-d
mailing list