Why is dtor called for lazy parameter?
andrey.zherikov at gmail.com
Fri Sep 18 12:32:49 UTC 2020
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
>> 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 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.
> : https://dlang.org/library/std/typecons/scoped.html
I modified do_lazy in this way:
auto do_lazy(lazy S s)
scope(exit) writeln("<- ",__PRETTY_FUNCTION__);
auto s1 = s;
The output is:
-> void test.main()
-> test.do_lazy(lazy S s)
1 S test.S.this(int n)
1 void test.S.~this()
<- 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
More information about the Digitalmars-d-learn