Actual lifetime of static array slices?

Ali Çehreli acehreli at yahoo.com
Tue Nov 15 06:44:16 UTC 2022


On 11/14/22 19:05, Elfstone wrote:

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

That is trivial for the compiler to catch.

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

That one requires the computer to analyze the code to a deeper level. 
Yes, we are passing a slice to the A constructor but we don't know 
whether the constructor will store the slice or simply use it. Even the 
following can be safe but impossible to detect by the compiler:

class A
{
     @safe
     this(int[] inData)
     {
         data = someCondition() ? new int[42] : inData; // (1)
         // ...
         if (someOtherCondition()) {
             data = null;                               // (2)
         }
     }
     // ...
}

(1) Whether we use inData depends on someCondition(). It may be so that 
bar() is never called depending on someCondition() in the program at all.

(2) data may never refer to 'static_array' after the constructor exits 
depending on someOtherCondition()

The code above may not be using good coding practices and humans may see 
the bugs if there are any but only a slow (infinetely?) compiler can see 
through all the code. (I think @live will help with these cases.) 
Further, the support for "separate compilation" makes it impossible to 
see through function boundaries.

Additionally, we don't want the compiler to force us to copy all stack 
variables just in case.

In summary, you are right but the compiler cannot do anything about it 
in all cases and we wouldn't want it to spend infinite amount of time to 
try to determine everything.

Ali



More information about the Digitalmars-d-learn mailing list