[Dlang-study] [lifetime] Initial thoughts on lifetime management
Timon Gehr
timon.gehr at gmx.ch
Wed Oct 28 11:00:31 PDT 2015
On 10/28/2015 06:21 PM, Andrei Alexandrescu wrote:
> On 10/28/2015 12:24 PM, Marc Schütz wrote:
>> Globals are just a special case, though. Rewriting your example without
>> globals:
>>
>> void bar() {
>> C c = new C();
>> foo(c, c);
>> }
>>
>> int foo(ref C c, scope C d) {
>> c = new C(); // c's old instance gets deleted
>> return d.i; // oops! d is invalid
>> }
>
> Yah, the thing is direct passing is easily under the control of the
> compiler. With some made-up notation, the compiler could do something
> like this:
>
> void bar() {
> C c = new C();
> [[auto __t = c; __t.refs += 2;]]
> foo(c, c);
> [[__t.refs -= 2;]]
> }
+=2 seems arbitrary. Only one new reference is generated.
Anyway, the solution is indeed to make it the responsibility of the
caller to keep the borrowed object alive. I.e. when passing a non-scope
reference to a scope argument, the reference count must be increased for
the duration of the call. The benefit is that scope references can be
duplicated arbitrarily without updating the reference count.
This applies to globals just as well as to other cases.
(I haven't read DIP74 though, so I might be misinterpreting your
intentions.)
(Note that here, it would be unproblematic to allow assigning scope
references to non-scope references given that the reference count is
increased, but that's not the meaning of scope.)
More information about the Dlang-study
mailing list