static array with inferred size

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Sep 20 07:38:00 UTC 2017


On Wednesday, September 20, 2017 07:12:15 Dgame via Digitalmars-d wrote:
> On Wednesday, 20 September 2017 at 05:36:43 UTC, Andrei
>
> Alexandrescu wrote:
> > On 9/19/17 8:47 PM, Steven Schveighoffer wrote:
> >> This needs to happen.
> >>
> >> e.g.:
> >>
> >> char[$] arr = "hello"; // syntax up for debate, but I like
> >> this.
> >>
> >> I can't think of a correct way to do this that doesn't
> >> heap-allocate and is DRY.
> >>
> >> D is so powerful, it's a huge shame it can't figure this one
> >> out.
> >>
> >> issue: https://issues.dlang.org/show_bug.cgi?id=481
> >>
> >> Fix that was merged: https://github.com/dlang/dmd/pull/3615
> >>
> >> And then reverted: https://github.com/dlang/dmd/pull/4373
> >>
> >> Maybe there was an issue with the implementation? Can it be
> >> redone?
> >>
> >> -Steve
> >
> > The argument was it can be done trivially with a library
> > solution. -- Andrei
>
> http://p0nce.github.io/d-idioms/#@nogc-Array-Literals:-Breaking-the-Limits

Yeah, it's a partial solution, but it won't work with VRP. e.g.

ubyte[4] = [1, 2, 3, 4];

is legal, but that won't work with that template.

https://issues.dlang.org/show_bug.cgi?id=16779

Also, that example

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

    // Use myDynamicArray...
}

looks like it shouldn't even be legal, since the static array should be gone
as soon as the line where myDynamicArray is declared has passed. Using auto
should be fine, because then it would be a static array, and the data would
be copied to the stack, but assigning it to a dynamic array should be
illegal.

- Jonathan M Davis



More information about the Digitalmars-d mailing list