Obtain pointer from static array literal

Nicholas Wilson iamthewilsonator at hotmail.com
Fri Oct 8 06:59:32 UTC 2021

On Friday, 8 October 2021 at 05:31:21 UTC, codic wrote:
> On Friday, 8 October 2021 at 05:01:00 UTC, Nicholas Wilson 
> wrote:
>> note that if the pointer is not escaped from the function 
>> (i.e. thing is void thing(scope int* abc)note the addition of 
>> scope) LDC will perform promotion of GC allocation to stack of 
>> the array literal even if you don't use .staticArray.

> Interesting, I think you meant "even if you do use 
> .staticArray";

No, I meant what I said. The array literal will cause a GC 
allocation, unless it is assigned to a static array of the same 
length or is inferred to be a static array. The latter happens 
when you pass it to `staticArray` because staticArray takes a 
static array as a parameter and the literal is inferred to be 
static array instead of a dynamic array, which is the default.

> not sure why it would do that,

When you _don't_ use staticArray, what happens is LDC looks at 
the allocation and the fact that the allocated memory does not 
escape the passed to function (because the argument is annotated 
with `scope`) and turns the GC allocated dynamic array literal 
into a stack allocation (assuming that the array is of 
sufficiently small size as to not blow the stack).

> but it doesn't  matter because my code is betterC

I guess the point is moot

> and therefore nogc so it  *should* allocate it on the stack, I 
> think

No, you can still try to use the GC in betterC but you will get a 
compile time error if you do so. Passing `-betterC` does not 
cause GC to stack promotion, it issues errors if you try to use 
GC (or any other feature that requires druntime like associative 
arrays or typeinfo).

More information about the Digitalmars-d-learn mailing list