Safety, undefined behavior, @safe, @trusted

Adam D. Ruppe destructionator at gmail.com
Thu Nov 5 13:40:11 PST 2009


On Thu, Nov 05, 2009 at 10:19:27PM +0100, Ary Borenszweig wrote:
> I don't want to think about 
> safety all the time, just let me code! If something is unsafe I'll mark 
> it for you, compiler, no problem, but do you think I'm just some crazy 
> unsafe maniac? I program safely.

This might be a problem. If safe functions can only call other safe functions
and all functions are safe by default, unsafe becomes viral.

Let me give an example:

void main() {
  doSomething();
  doSomethingElse();
}

void doSomething() { does safe things }
void doSomethingElse() { oneMoreFunction(); }

void oneMoreFunction() { byte* a = cast(byte*) 0xb80000000L; // unsafe!}


Now, to actually call oneMoreFunction, you have to mark it as unsafe. Then,
since it is called in doSomethingElse, you have to mark it as unsafe. Then,
since it is called from main, it too must be marked unsafe.

This would just get annoying.


This is bypassed by marking oneMoreFunction() as @trusted. Having an @unsafe
is unworkable in safe by default. It is just default (safe) and marked
(trusted).



Which is going to work best for existing code? With Walter's idea, you
compile it, then fix functions piece by piece to make them safe. Since your
other unsafe functions can still call them, the change is localized and you
get safer with each revision.

With safe by default, you'd probably make existing code compile just by
slapping @trusted: at the top and being done with it. That's not actually
safe - you're just telling the compiler to shut up about it.


-- 
Adam D. Ruppe
http://arsdnet.net



More information about the Digitalmars-d mailing list