Actual lifetime of static array slices?

Elfstone elfstone at yeah.net
Tue Nov 15 02:26:41 UTC 2022


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.

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?


More information about the Digitalmars-d-learn mailing list