ref is unsafe

Sönke Ludwig sludwig at outerproduct.org
Thu Jan 3 22:30:46 PST 2013


Am 03.01.2013 00:48, schrieb Jason House:
> On Sunday, 30 December 2012 at 08:38:27 UTC, Jonathan M Davis wrote:
>> After some recent discussions relating to auto ref and const ref, I have come
>> to the conlusion that as it stands, ref is not @safe. It's @system. And I
>> think that we need to take a serious look at it to see what we can do to make
>> it @safe. The problem is combining code that takes ref parameters with code
>> that returns by ref.
> 
> The best solution I can think of is for the @safe code to require a ref return value is treated with
> the same care as all the function input arguments. I'll try to annotate the example code you gave to
> explain.
> 

+1

In other words, references returned by a function call that took any references to locals would be
tainted as possibly local (in the function local data flow) and thus are not allowed to escape the
scope. References derived from non-local refs could still be returned and returning references to
fields from a struct method also works.

---
@safe ref int test(ref int v) {
	return v; // fine
}

@safe ref int test2() {
	int local;
	return test(local); // error: (possibly) returning ref to local
}

@safe ref int test3() {
	int local;
	int* ptr = &test(local); // fine, ptr is tainted 'local'
	return *ptr; // error: (possibly) returning ref to local
}

@safe ref int test4(ref int val) {
	return test(val); // fine, can only be a ref to the external 'val' or to a global
}
---


More information about the Digitalmars-d mailing list