Code Safety Attributes

You will learn about the code safety attributes that a function provides in this lesson.

@safe, @trusted, and @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 auto functions.

@safe functions

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 @safe functions:

  • Pointers cannot be converted to other pointer types other than void*.

  • 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 @system cannot be called.

  • Exceptions that are not descended from Exception cannot 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.

  • __gshared variables cannot be accessed.

@trusted functions

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 @trusted code.

@system functions

Any function that is not marked as @safe or @trusted is considered @system, which is the default safety attribute.


Get hands-on with 1400+ tech skills courses.