ref is unsafe

Rob T rob at ucora.com
Sun Dec 30 17:37:56 PST 2012


On Sunday, 30 December 2012 at 22:30:24 UTC, Jonathan M Davis 
wrote:
> On Sunday, December 30, 2012 23:18:43 jerro wrote:
>> > Honestly though, I'm inclined to argue that functions which
>> > return by ref and
>> > have a ref parameter of that same type just be considered
>> > @system.
>> 
>> What about this:
>> 
>> struct Foo
>> {
>>      int a;
>> }
>> 
>> ref int bar(ref Foo foo)
>> {
>>      return foo.a;
>> }
>> 
>> the parameter type and the return type here are different, but
>> bar still returns a reference to its parameter. I guess you
>> should consider all functions that return ref and have at least
>> one ref parameter @system (unless they are marked @trusted).
>
> Good point. Member variables of parameters also cause problems. 
> So, it very
> quickly devolves to any function which accepts a user-defined 
> type by ref and
> returns anything by ref would have to be @system, which is far 
> from pleasant.
>
> - Jonathan M Davis

This may be far fetched, but consider this,

If a function returns a ref that is the same as what was passed 
in by ref, then the passed and return addresses would match, 
which means that it still may be possible for the compiler to 
detect the situation.

This is more complicated in the case where a user defined struct 
was passed by ref, and the ref return type is a member from that 
struct, but it still may be possible to detect it.

If address matching is possible (or is that determined only at 
link time?) then it may be possible to detect a situation that 
should be illegal and flagged as a compiler error.

--rt




More information about the Digitalmars-d mailing list