An important potential change to the language: transitory ref

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sat Mar 20 09:41:48 PDT 2010


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.

> I agree it's a goal worth pursuing, but we sure need new idiom to
> replace the one above. I think I see a solution: force the caller to
> provide a delegate when he wants to access and act on a reference. In
> the following example, the reference can't escape beyond applyFront's
> scope, but the caller is still free to do whatever it wants, with the
> exception that it can't escape the ref outside of the delegate he provided.
>
> struct WrapperRange(R) {
> R wrappedRange;
> void applyFront(void delegate(ref ElementType!R) actor) {
> actor(wrappedRange.front);
> }
> }
>
> R range;
> // Instead of this:
> range.front.callSomeFunc();
> // Use this:
> range.applyFront!((ref ElementType!R e) { e.callSomeFunc(); })();
>
> Perhaps the compiler could be of some help here, by adding some sugar in
> a similar way that foreach is transformed to opApply. Could the dot
> operator automatically do something of the sort?

I find that quite alembicated.


Andrei



More information about the Digitalmars-d mailing list