How to replicate an Error: scope variable `old` assigned to `ref` variable `ctx` with longer lifetime?

matheus matheus at gmail.com
Mon May 12 21:46:04 UTC 2025


I saw a post 
(https://forum.dlang.org/post/aklmfkzqpsraprjfxsjh@forum.dlang.org) by Dennis where he gives an example:

>Finally, mechanical scope checking has false positives:
>```D
>void f(ref scope S ctx)
>{
>    const old = ctx;
>    g(ctx);
>    ctx = old; // Error: scope variable `old` assigned to `ref` 
> variable `ctx` with longer lifetime
>
>}
>```

So I'd like to try it out, so I wrote the snippet below:

@safe

import std;

struct S{}

void f(ref scope S ctx) {
     const old = ctx;
     g(ctx);
     ctx = old;
}

void g(ref scope S ctx) {
     S a;
     ctx = a;
}

void main(){
    S i;
    f(i);
}

But no errors. I tried Class too and no errors again.

Could someone please show me how can a replicate?

Thanks,

Matheus.


More information about the Digitalmars-d-learn mailing list