@trusted and return ref

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 26 13:20:53 PST 2015


On 2/26/15 3:49 PM, "Ola Fosheim =?UTF-8?B?R3LDuHN0YWQi?= 
<ola.fosheim.grostad+dlang at gmail.com>" wrote:
> On Thursday, 26 February 2015 at 16:25:59 UTC, Steven Schveighoffer wrote:
>> First, malloc should be safe, in the same way new is safe.
>
> If it is typed and do the sizeof...

Right, one can easily make a @safe wrapper around malloc as long as free 
is never called :)

>
>> I would say THIS is somewhat correct:
>>
>> (() @trusted {free(count); count=null;})();
>>
>> This takes something that is validly safe, and keeps the safety by
>> ensuring the pointer is no longer dangling.
>>
>> However, we have an issue here. At any point inside the code, you
>> could do:
>>
>> oldcount = count;
>>
>> And now, there is still potentially a dangling pointer somewhere. This
>> means every place count is used must be checked. In this case, all
>> uses of count have to be re-checked when the file is edited.
>
> Yes, so count should only be accessible directly from @trusted. So you
> need to mark it "@trusted-only".

Right, the lure of @trusted delegates is that it does not take into 
account the leaking of memory details. You essentially make any @safe 
code that uses the same data as @trusted code now @trusted, but without 
a marking. It was the reason I was suggesting at one point that @trusted 
should internally mark variables as @trusted accessed so they could only 
be used in @trusted code.

Even with the suggestion I had above, the danger is still there for 
maintenance to this code to foil any guarantees made on the previous 
version.

>
>> This is a great example of why @trusted is mostly a convention thing,
>> and not an enforceable thing.
>
> Well, it would be enforceable if you had a proper type system built
> around it.

I'm not sure it's worth it. For something like RCSlice, it might just be 
good enough to mark the whole thing as @trusted, so the danger signs are 
put into the correct place. This is going to be a low-level primitive, 
that hopefully is fully encapsulated.

But of course, this is still by convention. I agree that any mechanical 
checking of @trusted is going to be impossible without a type notation 
for the data it touches.

I think one thing is for certain that I have learned through the 
discussions about @trusted -- we should avoid @trusted as much as 
possible in all code.

-Steve


More information about the Digitalmars-d-learn mailing list