Actual lifetime of static array slices?
Mike Parker
aldacron at gmail.com
Tue Nov 15 02:49:55 UTC 2022
On Tuesday, 15 November 2022 at 02:26:41 UTC, Elfstone wrote:
> I failed to find any documentation, except dynamic array slices
> will be taken care of by GC, but I assume it's not the case
> with static arrays.
A slice is a view on the existing memory owned by the original
array. No allocations are made for the slice. The GC will track
all references to the memory allocated for a dynamic array, so as
long as any slices remain alive, so will the original memory.
Static arrays are allocated on the stack and become invalid when
they leave a function scope. In turn, so would any slices or
other pointers that reference that stack memory.
>
> But the code bellow doesn't behave as I expected.
>
> int[] foo()
> {
> int[1024] static_array;
> // return static_array[]; // Error: returning
> `static_array[]` escapes a reference to local variable
> `static_array`
> return null;
> }
>
> class A
> {
> this(int[] inData)
> {
> data = inData;
> }
>
> int[] data;
> }
>
> void main()
> {
> int[] arr;
> A a;
> {
> int[1024] static_array;
> arr = aSlice; // OK
> a = new A(aSlice); // OK
> arr = foo();
> //arr = foo();
>
> }
> }
>
> By assigning aSlice to arr or a, it seemingly escapes the
> scope, I thought there'd be errors, but the code compiles just
> fine.
>
> Is it really safe though?
It's not the scope that matters here. It's the stack. Memory
allocated in the inner scope uses the function stack, so it's all
valid until the function exits.
More information about the Digitalmars-d-learn
mailing list