www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - DIP1000 and immutable

reply jmh530 <john.michael.hall gmail.com> writes:
What is the motivation for DIP1000 also applying to immutable?

For instance, in the code (compiled with -dip1000), adapted from 
the spec [1], you get the same errors with immutable function 
parameters as you would with mutable ones. However, should it 
ever matter if you escape an immutable?

```d
 safe:

void thorin(scope immutable(int)*) {}
void gloin(immutable(int)*) {}

immutable(int)* balin(scope immutable(int)* q)
{
     thorin(q);
     gloin(q); // error, gloin() escapes q
     return q; // error, cannot return 'scope' q
}

void main() {
     immutable(int) x = 2;
     immutable(int)* ptrx = &x;
     immutable(int)* ptrz = balin(ptrx);
}
```

I tried basically the same thing in Rust and it doesn't generate 
errors (their borrow checker should be assuming scope by default).

```rust


fn gloin(x: &i32) {
}

fn ballin(x: &i32) -> &i32 {
     gloin(x);
     return x;
}

fn main() {
     let x = 2;
     let ptrx = &x;
     let ptrz = ballin(ptrx);
}
```

[1] https://dlang.org/spec/function.html#scope-parameters
Apr 27 2021
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Tuesday, 27 April 2021 at 14:28:12 UTC, jmh530 wrote:
 However, should it ever matter if you escape an immutable?
Your example is a pretty clear case of use-after-free if gloin actually did escape the reference and kept it after main returned.
 I tried basically the same thing in Rust and it doesn't 
 generate errors (their borrow checker should be assuming scope 
 by default).
That means it treats gloin as if it is scope, so it isn't the same as your D code since the gloin there is NOT borrowing.
Apr 27 2021
parent jmh530 <john.michael.hall gmail.com> writes:
On Tuesday, 27 April 2021 at 14:44:48 UTC, Adam D. Ruppe wrote:
 On Tuesday, 27 April 2021 at 14:28:12 UTC, jmh530 wrote:
 However, should it ever matter if you escape an immutable?
Your example is a pretty clear case of use-after-free if gloin actually did escape the reference and kept it after main returned.
 I tried basically the same thing in Rust and it doesn't 
 generate errors (their borrow checker should be assuming scope 
 by default).
That means it treats gloin as if it is scope, so it isn't the same as your D code since the gloin there is NOT borrowing.
Hmmm, good points. Thanks.
Apr 27 2021