On Friday, 18 September 2020 at 11:31:39 UTC, Simen Kjærås wrote:
On Friday, 18 September 2020 at 10:43:47 UTC, Andrey Zherikov wrote:
Why is dtor called before returning from do_lazy function - see (1)? It seems cause uninitialized parameter in do_something call after it in (2)-(3).

As ikod mentions, it's because of scoped!S. As for why it does this, yeah, this is kinda egregious. The documentation[0] of scoped mentions this issue:

This facility is unsafe; it is the responsibility of the user to not escape a reference to the object outside the scope.

As the name implies, scoped!T limits the valid scope of a reference to the scope of the variable holding it. You're putting it on the stack, so the moment the variable goes off the stack (when do_lazy returns), the reference is destructed.

--
  Simen

[0]: https://dlang.org/library/std/typecons/scoped.html

I modified do_lazy in this way:
======
auto do_lazy(lazy S s)
{
    writeln("-> ",__PRETTY_FUNCTION__);
    scope(exit) writeln("<- ",__PRETTY_FUNCTION__);

    auto s1 = s;
    writeln("===",s1.i);       (1)

    return s1;
}
======
The output is:
======
-> void test.main()
-> test.do_lazy(lazy S s)
-> test.create()
1 S test.S.this(int n)
<- test.create()
1 void test.S.~this()
===-1                          (2)
<- test.do_lazy(lazy S s)
-> 1703096 test.do_something(S s)
<- 1703096 test.do_something(S s)
<- void test.main()
======

As you can see, dtor is called before writeln on (1) and s1.i is -1 (2)

Reply via email to