Shouldn't invalid references like this fail at compile time?

Steven Schveighoffer schveiguy at yahoo.com
Tue Jan 23 21:53:24 UTC 2018


On 1/22/18 11:11 PM, Mike Franklin wrote:
> On Tuesday, 23 January 2018 at 02:25:57 UTC, Mike Franklin wrote:
> 
>> Should `destroy` be `@system` so it can't be called in `@safe` code, 
>> or should the compiler be smart enough to figure out the flow control 
>> and throw an error?
> 
> Interestingly, `destroy` is an unsafe operation for classes.

Because it's calling a @system function, rt_finalize. This function 
calls whatever is in the destructor, and because it works on Object 
level, it has no idea what the actual attributes of the derived 
destructor are.

This needs to be fixed, but a whole host of issues like this exist with 
Object.

> But it's not an unsafe operation for structs

Because struct destructors are not virtual. The compiler can tell when a 
struct destructor is unsafe:

https://run.dlang.io/is/o3ujrP

Note, I had to call destroy in a sub-function because if I made main 
@safe, it would fail to compile due to automatic destruction.

> 
> Not sure if that's a bug or not.

Not a bug.

Also, as others have pointed out, null dereferences are also considered 
@safe [1]. destroying an object doesn't actually deallocate it. It puts 
it into a state that is @safe to call, but will likely crash.

On 1/22/18 9:43 PM, Nicholas Wilson wrote:
 >
 > The compiler should be taught that any access to a `.destroy()`ed object
 > is invalid i.e. that its lifetime ends when destroy is called.

destroy is just a function, there shouldn't be any special magic for it 
(we have enough of that already). And in fact its lifetime has not 
ended, it's just destructed, and left as an empty shell.

The idea behind destroy is to decouple destruction from deallocation (as 
delete combines the two). @safe is all about memory safety, nothing 
else. As long as you can't corrupt memory, it is @safe.

-Steve

[1] Note: the reason they are safe is because they generally result in a 
segfault, which doesn't harm any memory. This is very much a user-space 
POV, and doesn't take into account kernel-space where null dereferences 
may actually be valid memory! It also doesn't (currently) take into 
account possible huge objects that could extend into valid memory space, 
even in user space.


More information about the Digitalmars-d mailing list