Actual lifetime of static array slices?

Elfstone elfstone at yeah.net
Tue Nov 15 03:05:30 UTC 2022


On Tuesday, 15 November 2022 at 02:50:44 UTC, Siarhei Siamashka 
wrote:
> On Tuesday, 15 November 2022 at 02:26:41 UTC, Elfstone wrote:
>> 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?
>
> No, it's not safe. You can add `@safe:` line in the beginning 
> of your program and it will fail to compile (after renaming 
> static_array to aSlice):
>
>     test.d(27): Error: address of variable `aSlice` assigned to 
> `arr` with longer lifetime
>
> By default everything is assumed to be @system and the compiler 
> silently allows you to shoot yourself in the foot. See 
> https://dlang.org/spec/memory-safe-d.html

Thanks, @safe works my first code, but the following code still 
compiles.

     class A
     {
     	@safe
     	this(int[] inData)
     	{
     		data = inData;
     	}

     	int[] data;
     }

     @safe
     int[] foo()
     {
     	int[1024] static_array;
     	// return static_array[]; // Error: returning 
`static_array[]` escapes a reference to local variable 
`static_array`
	return null;
     }

     @safe
     A bar()
     {
     	int[1024] static_array;
     	return new A(static_array[]);
     }

     @safe
     void main()
     {
     	auto a = bar();
     	writeln(a.data); // OK, but writes garbage
     }

So the compiler detects escaping in foo() but not in bar(), this 
doesn't look right.

Is there a way to tell whether a slice is from a dynamic array or 
a static array?






More information about the Digitalmars-d-learn mailing list