[Dlang-study] [lifetime] Initial thoughts on lifetime management
Marc Schütz
schuetzm at gmx.net
Wed Oct 28 09:24:56 PDT 2015
On Wednesday, 28 October 2015 at 15:24:21 UTC, Andrei
Alexandrescu wrote:
> On 10/28/2015 11:15 AM, Marc Schütz wrote:
>> On Wednesday, 28 October 2015 at 00:46:34 UTC, Andrei
>> Alexandrescu wrote:
>>> I should add here another pattern that turned problematic for
>>> our
>>> older attempts in DIP74:
>>>
>>> C c = new C();
>>> foo(c);
>>>
>>> int foo(scope C d) {
>>> c = new C(); // c's old instance gets deleted
>>> return d.i; // oops! d is invalid
>>> }
>>>
>>
>> That's because global variables have potentially shared
>> ownership. They
>> need special treatment (for example, in Rust many things you
>> can do with
>> them require unsafe blocks). If `c` were an argument to `foo`,
>> the
>> compiler could catch the problem at the call site.
>
> Interesting. Would it be sensible to add a restriction that no
> @rc object can be reachable from a global? (At least in @safe
> code.)
>
> Without the restriction, it seems we always need to assume that
> any object is reachable via a global so we need to add a bunch
> of incs/decs.
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
}
RC elision may only be done if the call doesn't create new
mutable aliases to the owner.
More information about the Dlang-study
mailing list