ref parameters: there is no escape

Steven Schveighoffer schveiguy at yahoo.com
Mon Aug 15 06:33:39 PDT 2011


On Sun, 14 Aug 2011 10:20:37 -0400, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> 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!

It sounds reasonable, especially with the added clarification that you can  
cast yourself back to the good old unsafe pointer.

The one thing I'm leery of is that structs are passed by reference for  
member functions, which is *forced* by the compiler.

Not that it's going to be horrible, but I think in certain cases,  
especially for things that allocate structs on the heap, this is going to  
require a lot of casting.

Here is a real world example for dcollections that is full of &this:

http://www.dsource.org/projects/dcollections/browser/branches/d2/dcollections/Link.d#L37

Is there no way to say "for this section of code, allow taking reference  
addresses"?

-Steve


More information about the Digitalmars-d mailing list