ref for (const) variables

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 17 11:14:38 PDT 2015


On Tuesday, March 17, 2015 09:59:59 Namespace via Digitalmars-d-learn wrote:
> On Tuesday, 17 March 2015 at 09:56:09 UTC, Jonathan M Davis wrote:
> > On Monday, March 16, 2015 18:46:59 Namespace via
> > Digitalmars-d-learn wrote:
> >> May this be worth of an enhancement request? Or was this
> >> already
> >> rejected?
> >> And, no, I want no mutable references such as C++.
> >
> > Walter has been adamantly against having ref variables like C++
> > has. They're
> > a potential @safety issue and add a fair bit of complication to
> > the
> > language. I doubt that suggesting that we have them as
> > const-only would
> > change his mind any - especially since that addresses none of
> > the @safety
> > issues.
> >
> > - Jonathan M Davis
>
> If I can't mutate them, where are the @safety issues?

With regards to what they refer to. For instance,

ref const(Foo) getFoo();
ref const(Foo) foo = getFoo();

How long is the ref returned by getFoo even valid? Maybe it refers to memory
that gets freed on the next line. The compiler can't know. So, foo may or
may not stay valid, and so it's not @safe unless the compiler can guarantee
the lifetime of what foo refers to.

Or, take this example which (unfortunately) currently compiles:

ref int getBar(ref int bar) @safe
{
    return bar;
}

ref int getFoo() @safe
{
    int foo;
    return getBar(foo);
}

void main()
{
    getFoo() = 7;
}

By the time getFoo returns, what it's returning is already invalid. So, the
code _isn't_ @safe, even though the compiler claims it is. Allowing
something like

void main()
{
    ref const(int) foo = getFoo();
}

would just perpetuate the problem. What foo refers to is _already_ invalid
even without having to worry about whether it will stay valid when the code
after it does whatever it does.

I believe that the return attribute stuff that was recently added is
intended to solve these issues, but I haven't really looked at it much yet,
so I'm not very familiar with the details. And maybe those changes would
make it so that allowing ref variables would work. I don't know. But const
really isn't the issue. It's lifetime. It has to be guaranteed that what the
ref refers to is valid for at least as long as the ref is.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list