structs are now lvalues - what is with "auto ref"?

Jonathan M Davis jmdavisProg at gmx.com
Mon Dec 24 13:34:51 PST 2012


On Monday, December 24, 2012 16:08:36 Andrei Alexandrescu wrote:
> On 12/24/12 1:49 PM, Jonathan M Davis wrote:
> > On Monday, December 24, 2012 13:45:10 Andrei Alexandrescu wrote:
> Actually D's rules are different from C++'s in that regard; Walter
> mentioned D is more sanguine about destroying data. I'll check with him.

Well, that could be a problem.

> > It's being
> > able to do
> > 
> > const int&  i = foo(bar(min(5, 7)));
> > 
> > which would allow a reference to be kept around, which D disallows.
> 
> I now see what you mean, thanks. We need to disallow taking the address
> of that ref, but that's already planned.

Actually, one problem did occur to me after thinking about this some more.

ref int foo(ref int i)
{
    return i;
}

ref int bar(int j)
{
    return foo(j);
}

While the ref returned by bar can't be saved without being copied, it's 
returning a ref which isn't valid once bar has returned, since it was a 
function parameter which was not ref. The same would occur if you did

ref int baz()
{
    int i;
    return foo(i);
}

The ref has managed to basically do what happens with & and pointers, and it's 
essentially the same as

int* foo(int* i)
{
    return i;
}

int* bar(int j)
{
    return foo(&j);
}

You have an escaping reference. So, while the min example would be valid, 
because ref was used througout, if any part of the chain passed by value or if 
it was a local variable inside one of those functions which was returned by 
ref, then we're in trouble. And auto ref will have exactly the same problem. 
The fact that you can both pass by ref screws things up. If that were illegal, 
then we'd be okay, but it's not illegal, and it would be problematic if it 
were, since we'd end up with lots of unnecessary copies in quite a few cases.

I suppose that we could disallow returning by ref unless the value being 
returned was an actual variable (as opposed to the return value of another 
function which returned by ref), but I don't know how restrictive that would 
be.

Certainly, as things stand, the code above that uses ref is doing what would 
currently be considered @safe code even though it's actually unsafe. We 
definitely need to work through this some more and figure out what should and 
shouldn't be valid and what we can and can't make @safe.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list