ref parameters: there is no escape

Jakob Ovrum jakobovrum+ng at gmail.com
Mon Aug 15 21:09:47 PDT 2011


On 2011/08/16 12:33, Mehrdad wrote:
> On 8/15/2011 2:04 PM, Timon Gehr wrote:
>> On 08/15/2011 04:04 PM, Mehrdad wrote:
>>> On 8/15/2011 4:10 AM, Timon Gehr wrote: Because now you need pointers
>>> to pass things by reference?
>> Only if the function intends to escape the reference. And if you
>> really need to, you can still use a cast.
>
> ... introducing D#?
>
> void dangerous(ref int x)
> {
> unsafe
> {
> bar(&x);
> }
> }
>
> (i.e. "you can still use a cast" is pretty much equivalent to using C#'s
> unsafe block. Maybe C#'s done some things correctly after all, huh?...)
>
>> Furthermore, escaping a reference is generally unsafe when it is to
>> stack memory (they can be some higher-level invariant that guarantees
>> safety, but that is not within the compilers reach -- use a cast.)
>
> Right, so let's also ban "auto ref" as a return value, since it could be
> returning the parameter itself, without the caller's knowledge:
>
> 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.

>> When the reference is to a value type on heap memory, you had pointers
>> in your code all along.
> And that means...?
> Java and C# have had pointers all along, but they're pretty darn
> successful at rendering them useless *except* for interop purposes.
> Obviously, it looks as though D is failing to achieve that same goal,
> requiring pointers for something so simple -- do we really want that?
>

Java doesn't have pointers. (unless you're referring to its reference 
types, which you obviously aren't, considering your interop comment).

Pointers aren't required in D either, but are supported nevertheless, 
one reason being that D allows for putting value types directly on the 
heap, like structs and primitives, which C# doesn't.

>> Warnings are issued for constructs that are regarded as potentially
>> dangerous/error-prone by many people, but are still valid code.
>> Therefore, they usually reflect suboptimal language design.
>
> Is that why my C compiler issues "Warning: Uninitialized local variable
> p" when I run this?
>
> int *p;
> *p = 5;
>
> AFAIK this is clearly *INVALID* (i.e. undefined) code according to the
> standard...



More information about the Digitalmars-d mailing list