November 27, 2022

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:

@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.

December 15, 2022

On Saturday, 19 November 2022 at 15:24:33 UTC, Dukc wrote:

>

On Saturday, 19 November 2022 at 15:02:54 UTC, Nick Treleaven wrote:

>

OK, so how do I make lf implicitly scope?

Have the int* inside it to point to a local, or assign another scope int* to it.

Thanks, this works:

@safe:

struct S
{
    int* p;
    int[0] v; // dummy storage
    auto f() return @trusted => p ? p : v.ptr;
}

void main()
{
    int* p;
    {
        S s = S(new int);
        p = s.f; // error
    }
}
December 15, 2022

On Thursday, 15 December 2022 at 20:02:38 UTC, Nick Treleaven wrote:

>
auto f() return @trusted => p ? p : v.ptr;

Whoops, that can't be @trusted unless I assert(p).

1 2
Next ›   Last »