Why are scope variables being deprecated?

Jonathan M Davis jmdavisProg at gmx.com
Thu Jul 26 18:19:04 PDT 2012


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? You get undefined behavior, because foo 
doesn't exist anymore. If you really need foo to be on the stack, then maybe 
you should make it a struct. However, if you really do need scope for some 
reason, then you can use std.typecons.scoped, and it'll do the same thing.

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. So, they're being removed and put into the standard 
library instead.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list