On Friday, 25 November 2022 at 14:07:28 UTC, ShadoLight wrote:
On Saturday, 19 November 2022 at 14:07:59 UTC, Nick Treleaven
```d
@safe:

struct LockedFile
{
    private int* fps;

    auto fp() return scope => fps;
}

void main()
{
    int* p;
    {
        auto lf = LockedFile(new int);
        p = lf.fp;
    }
    assert(p != null); // address escaped
}
```
[snip]

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.

I find it a bit confusing what the term "lifetime" should pertain to in the case of variables declared inside a local scope inside a function - destructor invocation or physical existence of the variable on the stack?

But this has no bearing on the heap allocation and the lifetime of `p` in the example.

Reply via email to