ref is unsafe

deadalnix deadalnix at gmail.com
Fri Jan 4 05:46:16 PST 2013


On Friday, 4 January 2013 at 06:30:55 UTC, Sönke Ludwig wrote:
> 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
> }
>

v should be scope here. If not, other function have no guarantee 
that the reference will not escape.

> @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
> }
> ---

Given the modification mentioned above, this look like the way to 
go.


More information about the Digitalmars-d mailing list