On Wed, 11 Nov 2009 16:47:10 -0500, Walter Bright
<newshou...@digitalmars.com> wrote:
Consider the code:
@safe:
T[] foo(T[] a) { return a; }
T[] bar()
{
T[10] x;
return foo(x);
}
Now we've got an escaping reference to bar's stack. This is not memory
safe. But giving up slices is a heavy burden.
So it occurred to me that the same solution for closures can be used
here. If the address is taken of a stack variable in a safe function,
that variable is instead allocated on the heap. If a more advanced
compiler could prove that the address does not escape, it could be put
back on the stack.
The code will be a little slower, but it will be memory safe. This
change wouldn't be done in trusted or unsafe functions.
This sounds acceptable to me. In response to others making claims about
modifying behavior, you can get a safe function that can use unsafe
behavior by using @trusted if you wish.
I'm assuming this behavior translates to local non-array variables?
Can we allow the scope variable hack that is afforded for delegates:
@safe int sum(scope int[] a) { int retval = 0; foreach(i; a) retval += i;
return retval;}
This would not result in a heap allocation when called with a static array.
-Steve