Why are scope variables being deprecated?

Piotr Szturmaj bncrbme at jadamspam.pl
Wed Oct 10 08:04:41 PDT 2012


Jonathan M Davis wrote:
> On Thursday, July 26, 2012 21:09:09 Chad J wrote:
>> I keep hearing that scope variables are going away.  I missed the
>> discussion on it.  Why is this happening?
>>
>> When I read about this, I have these in mind:
>>
>> void someFunc()
>> {
>> 	// foo is very likely to get stack allocated
>> 	scope foo = new SomeClass();
>> 	foo.use();
>> 	// ~foo is called.
>> }
>
> It's inherently unsafe. What happens if you returned a reference to foo from
> someFunc? Or if you assigned a reference to foo to anything and then tried to
> use it after someFunc has returned?

Why scope parameters are not deprecated then? It's the same situation.

> You get undefined behavior, because foo
> doesn't exist anymore.

Excuse me, but no, compiler should prevent escaping scope references 
just like it does with scope parameters (I know it's currently 
implemented just for delegates).

> If you really need foo to be on the stack, then maybe
> you should make it a struct.

Then you lose some useful class features.

> scope on local variables is going away for pretty much the same reason that
> delete is. They're unsafe, and the fact that they're in the core language
> encourages their use.

That's not convincing for me. Pointers are also unsafe, and they're in
the core language.

 > However, if you really do need scope for some
 > reason, then you can use std.typecons.scoped, and it'll do the same 
thing.

scoped is more dangerous than language solution. See:

class A { }

__gshared A globalA;

static this()
{
     auto a = scoped!A;
     globalA = a;
}

and this compiles (http://dpaste.dzfl.pl/6c078e66). With scope storage 
class compiler would prevent this escaping assignment. It seems that we 
ended up with a solution that was meant to fix a language builtin but 
appears to be worse than that.


More information about the Digitalmars-d-learn mailing list