On 2011/08/14 23:20, Andrei Alexandrescu wrote:
Walter and I have had a long discussion and we thought we'd bring an
idea for community review.

We believe it would be useful for safety purposes to disallow escaping
addresses of ref parameters. Consider:

class C {
int * p;
this(ref int x) {
p = &x; // escapes the address of a ref parameter
}
}

Such code is accepted today. We believe it is error-prone and dangerous,
particularly because the caller has no syntactic cue that the address of
the parameter is passed into the function (in this case constructor).
Worse, such a function cannot be characterized as @safe.

So we want to make the above an error. The workaround is obvious - just
take int* as a parameter instead of ref int. What a function can do with
a ref parameter in general is:

* use it directly just like a local;

* pass it down to other functions (which may take it by value or
reference);

* pass its address down to pure functions because a pure function cannot
escape the address anyway (cool insight by Walter);

* take its address as long as the address doesn't outlive the frame of
the function.

The third bullet is not easy to implement as it requires flow analysis,
but we may start with a conservative version first. Probably there won't
be a lot of broken code anyway.

Please chime in with any comments you might have!


Thanks,

Andrei

I like the idea, but don't we already have (currently non-enforced) scope parameters for this? Of course it would be nice to have "ref" also mean scope, like "in" meaning "scope const", but it would be nice to have scope working properly.

Currently, this code compiles fine:
---------------------
const(char)[] test;

void foo(in char[] s)
{
        test = s;
}

void main()
{
        foo("bar");
}
----------------------
This is a big problem when writing a library (accepting delegate callbacks and such) and you're not sure whether the user wants to just "read" a variable or hold onto it. Whether or not to make a copy should be the user's choice, not the library's.

Reply via email to