Code Safety Attributes
@system are about the code safety that a function provides. As with purity, the compiler infers the safety level of templates, delegates, anonymous functions, and
A class of programming errors involves corrupting data at unrelated locations in memory by writing at those locations unintentionally. Such errors are mostly due to mistakes made in using pointers and applying type casts.
@safe functions guarantee that they do not contain any operation that may corrupt memory. The compiler does not allow the following operations in
Pointers cannot be converted to other pointer types other than
A non-pointer expression cannot be converted to a pointer value.
Pointer values cannot be changed (No pointer arithmetic is allowed; however, assigning a pointer to another pointer of the same type is safe.)
Unions that have pointer or reference members cannot be used.
Functions marked as
@systemcannot be called.
Exceptions that are not descended from
Exceptioncannot be caught.
Inline assembler cannot be used.
Mutable variables cannot be cast to immutable.
Immutable variables cannot be cast to mutable.
Thread-local variables cannot be cast to shared.
Shared variables cannot be cast to thread-local.
Addresses of function-local variables cannot be taken.
__gsharedvariables cannot be accessed.
Some functions may actually be safe but cannot be marked as
@safe for various reasons. For example, a function may have to call a library written in C, where no language support exists for safety in that language.
Some other functions may actually perform operations that are not allowed in
@safe code, but they may be well tested and trusted to be correct.
@trusted is an attribute that communicates to the compiler that although the function cannot be marked as
@safe, consider it safe. The compiler trusts the programmer and treats
@trusted code as if it is safe. For example, it allows
@safe code to call
Any function that is not marked as
@trusted is considered
@system, which is the default safety attribute.