On Friday, 25 November 2022 at 15:03:57 UTC, ShadoLight wrote:
I don't grok how `lf` can survive the local scope. Or am I missing something?

Perhaps because the local scope is not pushed as a separate (anonymous) function on the stack... if true then, yes, then `lf` will indeed have the same physical lifetime as main (and `p`)...?

On the other hand, if you add a destructor to `LockedFile`, it will be invoked at the end of the local scope, not the end of main.

Yes, the actual code does have a destructor. It's analogous to this:

```d
@safe:

struct S
{
    private int* fps;

    auto fp() return scope => fps;

    this(int)
    {
        fps = new int;
    }

    @disable this();
    @disable void opAssign(S);

    ~this() @trusted // how do we make this safe?
    {
        import core.memory;
        GC.free(fps);
    }
}

void main()
{
    int* p;
    {
        auto lf = S(5);
        p = lf.fp;
    }
    assert(p != null); // address escaped
}
```

That compiles with -dip1000. D doesn't seem to have a way to prevent the memory outliving the struct.

Just to note there is another problem when the struct is destroyed explicitly whilst the `fp` result is still live. But that could be solved by making `object.destroy` and `std.algorithm.move` be restricted to @system for certain structs like this one (either opt-in or some other mechanism). The first problem doesn't seem to have a solution.

Reply via email to