On 03/19/2010 10:52 PM, Michel Fortin wrote:
On 2010-03-19 22:56:59 -0400, Andrei Alexandrescu
<[email protected]> said:
So I was thinking of the following: how about still returning a
reference, but define a rule in the language that references can't
escape - you can't take their address and squirrel it away; the only
thing you can do is use them right on the spot or pass them down to
functions.
Can functions return the reference, or a reference to a part of the
original referenced value?
I see two possible approaches (a) disallow that, which I think would be
irregular, and (b) conservatively assume that that happens on the call side.
There is one other problem that I haven't mentioned. Consider the code:
void fun(ref int a, int b) {
a = b;
}
Array!int arr;
arr.resize(5);
fun(arr[4], (arr.resize(10000), 42));
The purpose of restricting ref was to allow Array to entirely
encapsulate its memory allocation, i.e. allow Array to use malloc and
free without fearing that someone still holds a dangling pointer in there.
In the code above, however, evaluation will first take the address of
arr[4] and _then_ call arr.resize (which may trigger reallocation). As a
consequence, by the time fun sees the ref, it's already dangling. I
don't know how to solve this.
Andrei