Impressed

Jonathan M Davis jmdavisProg at gmx.com
Thu Jul 26 19:13:08 PDT 2012


On Friday, July 27, 2012 04:00:56 Stuart wrote:
> On Friday, 27 July 2012 at 00:25:49 UTC, Jonathan M Davis wrote:
> > scope on local variables is going to be deprecated, because
> > it's unsafe.
> 
> Um...could you explain why? I thought scope on locals was a
> really nice feature. I was looking forward to making use of it
> for deterministic resource deallocation.

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.

> Besides, if scope(exit) is still allowed, how is that any different?

scope(exit) doesn't necessarily have anything to do with deallocating memory. 
It's far more general than that. It just runs an arbitrary statement when 
exiting the scope that it's declared in. There's nothing inherently unsafe 
about that. You _can_ do unsafe operations in it, but you can do that pretty 
much anywhere. So, if you were to free GC-allocated memory in a scope 
statement, then you'd be in exactly the same sinking boat that scope puts you 
in.

Freeing GC-allocated memory is inherently unsafe. It's the GC's job to do 
that. If you really want to be managing memory yourself, then you should be 
using malloc and free. But for those occasions when you really do end up 
needing that sort of control with GC memory, we have stuff like 
std.typecons.scoped and core.memory. They just shouldn't be used under normal 
circumstances, and you have to be careful with them, so you should only used 
them when you know what you're doing - which is in stark contrast to having 
delete and scope in the core language where everyone sees them and thinks that 
they're perfectly safe to use, completely ignoring or being completely unaware 
of the dangers involved. We give you the power to blow your foot off if you 
want to, but we don't want to prime the gun and hand it to you, just make it 
available if you need it.

- Jonathan M Davis


More information about the Digitalmars-d mailing list