On 2013-09-01 01:09, Andrei Alexandrescu wrote:

Oh I see. Yes, if we do find a way to define scope to provide
guarantees, that would be awesome.

How about this:

Object bar ()
{
    scope a = new Object;
    return a;
}

void main ()
{
    bar();
}

In the above code the compiler can determine that it's unsafe to return "a", with the following error:

Error: escaping reference to scope local a

So apparently it can do some form of limited escape analysis. But it's quite easy to fool the compiler. The example below won't result in any compiler errors.

Object foo (Object o)
{
    return o;
}

Object bar ()
{
    scope a = new Object;
    return foo(a);
}

void main ()
{
    bar();
}

What if we can help the compiler a bit. If we want to pass a scope object to another function it's required that the function takes the parameter as "scope", like this:

Object foo (scope Object o)
{
    return o;
}

Object bar ()
{
    scope a = new Object;
    return foo(a);
}

void main ()
{
    bar();
}

Now the compiler knows the "o" in "foo" is scope allocated and will perform the same analysis it did in the first example. This time the error will appear in "foo" and not in "bar".

Perhaps we can allow returning scope allocated objects as well if the function is marked as such:

scope(Object) foo (scope Object o)
{
    return o;
}

Object bar ()
{
    scope a = new Object;
    return foo(a);
}

void main ()
{
    bar();
}

Now the error will appear again in "bar" since it doesn't return a scope object.

--
/Jacob Carlborg

Reply via email to