An important potential change to the language: transitory ref

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sat Mar 20 15:24:58 PDT 2010


On 03/20/2010 12:30 PM, Michel Fortin wrote:
> On 2010-03-20 12:41:48 -0400, Andrei Alexandrescu
> <SeeWebsiteForEmail at erdani.org> said:
>
>> On 03/20/2010 06:53 AM, Michel Fortin wrote:
>>> On 2010-03-20 02:53:50 -0400, Andrei Alexandrescu
>>> <SeeWebsiteForEmail at erdani.org> said:
>>>
>>>> Perhaps it means you can't return ref returns from other functions if
>>>> you pass them references to local state.
>>>
>>> You realize you're doing that all over the place in std.range when a
>>> range wraps another one?
>>>
>>> struct WrapperRange(R) {
>>> R wrappedRange;
>>> ref ElementType!R front() {
>>> return wrappedRange.front();
>>> }
>>> }
>>>
>>> How do you plan to implement that in your proposed ref regime? Member
>>> functions receive 'this' as a ref argument, so they can't return a ref
>>> don't they?
>>
>> Hmmm, I think returning a ref to a member should be allowed as long as
>> the compiler realizes that ref has the same scope as the struct it
>> originated from.
>
> Ok, so the compiler assumes that the scope of the ref returned by
> function is the same as its ref arguments and prevent you from returning
> a ref to it if one of the ref argument is a local variable?
>
> That could work. It'd only become a hindrance in the more complex cases
> where you have multiple ref arguments in a function and no way to tell
> which one the returned ref comes from.

Yes. Conservatively, the scope of a returned ref is the smallest of all 
parameters involved, including 'this'.

There are two touches that Walter and I discussed:

a) You only need to keep in that set the parameters with .sizeof greater 
than or equal to the return type;

b) You only need to keep in that set the parameters that contain a 
direct subobject of the return type.

The rules are a bit odd, but they do the job and most importantly enable 
important encapsulation mechanisms.


Andrei



More information about the Digitalmars-d mailing list