ref parameters: there is no escape

Mehrdad wfunction at hotmail.com
Mon Aug 15 21:48:39 PDT 2011


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:

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?
}

>>> 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...

>>> 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?


More information about the Digitalmars-d mailing list