Skip to content
This repository has been archived by the owner on Jun 6, 2021. It is now read-only.

Note: Pointer Types and Casts

alexrp edited this page Mar 7, 2013 · 6 revisions

First a brief explanation of pointer types:

  • *T: Raw pointer to T. Can be null.
  • @T: Pointer to T. Has a managed header. Cannot be null.
  • &T: Pointer to T. Possibly offset by header size. Cannot be null.

Allowed casts and their safety:

  • @T as *T: Unsafe. Compiles to: res = ptr
  • @T as &T: Safe and implicit. Compiles to: res = ptr + header_size
  • *T as @T: Unsafe. Null-checked at runtime. Compiles to: res = ptr
  • *T as &T: Safe (mostly). Null-checked at runtime. Compiles to: res = ptr
  • &T as @T: Unsafe. Compiles to: res = ptr - header_size
  • &T as *T: Unsafe. Compiles to: res = ptr

The assumption is that people will be using &T in 99% of cases and will only use @T when they specifically need managed semantics (i.e. pointers point directly into the object, pointers cannot be substituted for unsafe pointers, etc) or *T when they need to do raw pointer arithmetic and such.

Casts from &T to @T or *T have to be unsafe because there's no way to tell if an &T pointer is actually a @T or a *T. This shouldn't be a problem in practice given the above assumption.

The address-of operator (&) is always considered unsafe and yields *T. References to fields, variables, or array/vector elements can be passed safely to functions by passing them with ref.

Clone this wiki locally