[Issue 22270] [DIP1000] class does infer scope in methods when assigned to a scope variable

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Sep 3 21:00:36 UTC 2021


https://issues.dlang.org/show_bug.cgi?id=22270

--- Comment #6 from Dennis <dkorpel at live.nl> ---
(In reply to João Lourenço from comment #4)
> So, how can I achieve something like this while instantiating a class or
> struct with scope in @safe code?

You can't do that with @safe and dip1000 currently, because scope is only one
layer. Making bar scope means making the array `somePointerToRestrictThis`
scope, so dummy creates a pointer to a scope array which can't be expressed.
What you can do is encapsulate `bar` in Wrapper and only give `return scope`
access, and mark dummy @trusted:

```
struct Bar
{
    int[] somePointerToRestrictThis;

    @trusted Wrapper dummy() return scope {
        Wrapper wrapper = { bar: &this };
        return wrapper;
    }
}

struct Wrapper
{
    private Bar* bar;

    // Must be explicitly `return scope` for our @trusted assumption
    @safe int[] access() return scope {
        return bar.somePointerToRestrictThis;
    }
}
```

But of course you're on your own ensuring there's no holes in your @trusted
code.


> Shouldn't scope with struct instances behave the same way as a normal
> instantiation though? The example above works if I don't instantiate 
> with scope.

Not entirely sure what you mean, but return scope means scope in, scope out. If
the input is not scope (and thus is assumed to have infinite lifetime), then
the output does not need to have lifetime restrictions either.

--


More information about the Digitalmars-d-bugs mailing list