An important potential change to the language: transitory ref

Michel Fortin michel.fortin at michelf.com
Sat Mar 20 04:53:34 PDT 2010


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?

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?


-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list