ref parameters: there is no escape

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sun Aug 14 09:54:03 PDT 2011


On 8/14/11 10:41 AM, dsimcha wrote:
> Another example of why this is a bad idea:
>
> In std.parallelism, I have a function called TaskPool.put, which takes a
> Task object by reference, takes its address and puts it on the task
> queue. This is used for scoped tasks. However, it's safe because Task
> has a destructor that waits for the task to be finished and out of the
> task queue before destroying the stack frame it's on and returning.

I understand. Would it be agreeable to require a cast to take the 
address of the parameter since you're relying on an extralinguistic 
invariant? Basically you'd be more motivated to do so if you recognized 
how problematic escaping ref parameters is for most cases.

> Why can't we just establish a strong convention that, if a function
> truly escapes the address of a ref parameter (meaning it actually lives
> longer than the lifetime of the function), you take a pointer instead of
> a ref? It's not like escaping ref parameters unintentionally is a common
> source of bugs.

Convention has its usefulness, but also major downsides. The problem 
here is that we can't verify (or infer) @safe for a lot of functions. 
Basically all functions taking ref become very difficult to use from 
safe code, including the common idiom of passing a stack variable into a 
function by reference. I don't think we can afford to lose so much when 
turning safety on.

> My point is that any rule we come up with will always be conservative. D
> is a **systems language** and needs to give the benefit of the doubt to
> assuming the programmer knows what he/she is doing. If you want extra
> checks, that's what SafeD is for.

I have only little sympathy for this argument; it actually leaves me 
more convinced we're on the right path. We're not talking about making 
it impossible to do something that you want to do. We're discussing 
about a change that will make a lot of functions efficient _and_ safe, 
leaving a minority of cases to a slight syntactic change.


Andrei


More information about the Digitalmars-d mailing list