[Dlang-study] [lifetime] Initial thoughts on lifetime management

Timon Gehr timon.gehr at gmx.ch
Thu Oct 29 09:14:08 PDT 2015


On 10/29/2015 03:33 PM, Michel Fortin wrote:
> Le 28 oct. 2015 à 20:47, Timon Gehr <timon.gehr at gmx.ch> a écrit :
>
>> On 10/29/2015 01:35 AM, Michel Fortin wrote:
>>> Le 28 oct. 2015 à 18:39, Timon Gehr <timon.gehr at gmx.ch> a écrit :
>>>
>>>> Actually, we do not need #references <= count.
>>>> It's just (#references > 0) -> (count > 0).
>>>> (The converse should also hold, but then #references has to include cyclic references.)
>>>
>>> There's still some value in knowing that the total number of references is 1 and not something higher.
>>>
>>> Swift has `isUniquelyReferenced` you can use to implement copy-on-write value types in a thread-safe way.
>>> I'm not entirely sure why they can guaranty uniqueness for Swift classes; it looks like they can't when
>>> it comes to Objective-C classes.
>>
>> Good point. However, it seems somewhat costly to support for classes that don't need it.
>
> I think I understand how Swift's `isUniquelyReferenced` works. It's not costly. It's also quite clever. I'll rewrite the function signature to its D equivalent for this discussion:
>
> 	bool isUniquelyReferenced(ref Object o);
>
> This function simply returns true if the counter for "o" is 1.

By somewhat costly, I mean that it prevents transformations that do not 
satisfy (#references=1) <-> (count=1).


> Note that the parameter is 'ref' to avoid the counter being incremented when passing the object to the function. It is also imperative that you do NOT make it 'const ref' if you want the function to work in the presence of the optimizer. By telling the compiler in the function signature that it might mutate the variable, it prevents opInc/opDec elision from occurring in the caller's context. I'll try to illustrate.
>...
>
> Ingenious.
>
>

It's what I'd call a hack though. :o)
It does not work well with inlining.


More information about the Dlang-study mailing list