ref parameters: there is no escape

Jakob Ovrum jakobovrum+ng at gmail.com
Tue Aug 16 00:27:59 PDT 2011


On 2011/08/16 13:48, Mehrdad wrote:
> On 8/15/2011 9:09 PM, Jakob Ovrum wrote:
>> On 2011/08/16 12:33, Mehrdad wrote:
>>> auto ref trySomethingExpensive(T)(auto ref T input, bool condition)
>>> {
>>> return condition ? doSomethingExpensive(input) : input; // Optimize
>>> the input
>>> }
>>> Thoughts? Should we ban ref return types, too?
>> No reference to stack memory can escape its stack frame in your example.
>> I don't see how this has anything to do with the discussion.
>
> Oh, I assumed it was obvious that you usually have to /call/ a function
> for anything to happen. But perhaps it wasn't, my bad.
> Here's something (hopefully) more obvious/verbose:

Not all calls to that function would be dangerous. I would even go so 
far as to claim most uses of such a function would not be dangerous. No 
need to be snarky, anyway.

>
> auto ref call_if(T)(auto ref T input, bool cond) {
> return cond ? call_something(input) : input;
> }
>
> ref int get_foo(int s) {
> int a = 9.8 * s;
> return call_if(x, true); // oops?
> }
>
> void test() {
> writeln(GetFoo()); // <--- what do you suppose gets returned?
> }
>

I agree these cases are problematic too, but disallowing escaping of ref 
parameters does not affect them. I don't think Andrei's suggestion 
includes disallowing returning ref parameters by ref, if it does, I 
agree that it would reduce the usefulness of ref return.

>>>> When the reference is to a value type on heap memory, you had
>>>> pointers in your code all along.
>>> Java and C# have had pointers all along <snip>
>> Java doesn't have pointers. <snip>
> If you consider references to be the same as pointers then surely you
> had pointers in your Java code all along?
>
>> Pointers aren't required in D either.
> It seems like they will be, after Andrei gets this working...
>

Things will work the same, except you'll need an explicit cast if you 
want to take the address of the ref parameter (which, as before, yields 
a pointer). You shouldn't take the address of ref parameters unless 
you're sure it's safe (but you seem to agree on this, with your C# 
unsafe example).

>>>> Warnings are issued for constructs that are regarded as potentially
>>>> dangerous/error-prone by many people, but are still valid code.
>>> int *p;
>>> *p = 5;
>>> AFAIK this is clearly *INVALID* (i.e. undefined) code according to
>>> the standard...
>
> Would be curious to know why you just ignored that comment, btw. Do you
> really consider that to be "valid" code, in any sense of the term?

I'm not the one who said it was...


More information about the Digitalmars-d mailing list