Alternative to Rust's borrow checking and explicit lifetimes?

Walter Bright newshound2 at digitalmars.com
Thu Apr 16 08:40:37 UTC 2020


On 4/15/2020 7:39 PM, Timon Gehr wrote:
> On 14.04.20 12:18, Walter Bright wrote:
>> does do NLL, and uses Data Flow Analysis to achieve it.
> Do you have an example where that helps?

int* malloc();
void free(int*);

@live void test()
{
     auto p = malloc(); // p is owner
     *p = 1;
     scope q = p; // q borrows p
     int x = *q;  // read from borrow
     *p = 2;      // using p again ends lifetime of q, even though q is in scope
     x = *q;      // error, q is no longer valid
     free(p);
}


> void ignore(int* p){}
> void main()@live{
>      int x=5;
>      auto p=&x;
>      x=3; // should fail, but compiles
>      *p=4;
>      ignore(p); // not necessary in Rust
> }
> 
> void ignore(int* p){}
> void main()@live{
>      int x=5;
>      auto p=&x;
>      *p=4;
>      x=3;
>      ignore(p); // not necessary in Rust
> }
> 
> Maybe the problem is that taking a local variable's address results in an owning 
> pointer instead of a borrowing pointer, but that would not make any sense. How 
> can a pointer ever own stack memory? Also, it appears that in a @safe function, 
> it is impossible to ever dispose of such a pointer as it is both `scope` and has 
> to be freed explicitly.
> 
> @live also allows the address of the same local variable to be taken multiple 
> times:
> 
> void main()@live{
>      int x=5;
>      auto p=&x;
>      auto q=&x;
>      *p=4;
>      *q=5;
>      writeln(*p," ",*q);
>      ignore(p);
>      ignore(q);
> }

You're right that taking the address of a local currently results in an owning 
pointer. I'll think about the best way to deal with this. Though note that if 
@safe is also added to the function, taking the address of a local is disallowed.



More information about the Digitalmars-d mailing list