Deref and Pointers (v0.2.1)
Pointer access, references, and dereference operations.
Latest
Overview
Pointers refer to memory by address. Dereference operations read or write the value stored at that address.
Because pointer mistakes are easy to make, Thrust keeps reference and dereference syntax visible in source.
Check pointers before dereferencing them, and keep raw pointer code small when possible.
Primary source: syntax/deref/
Syntax Signatures
var number: s32 = 42;
var pointer: ptr[s32] = ref number;
var value: s32 = (deref pointer);
Behavior and Use
Dereferencing nullptr or another invalid pointer is unsafe. Validate pointers before using them.
Pointer indexing should stay close to the code that knows the buffer size and layout.
Best Practices
- Check pointers for null before dereference.
- Keep pointer arithmetic in small, well-explained blocks.
- Copy pointed values into locals when that makes the code simpler.
References and Dereference
ref and deref make address-taking and memory reads explicit.
- ref value creates a pointer to storage that already exists.
- deref pointer reads the value at the pointer location.
- Writing through a pointer changes the storage reached by that pointer, not a copy.
Pointer Indexing
Indexing a pointer or array relies on a valid base and a valid element offset.
- Check for nullptr before dereferencing pointers from external code or allocation routines.
- Keep the length or capacity used for bounds checks near the indexing code.
- Use typed pointers when possible so the element type is visible at the access site.
Example
fn readOrZero(pointer: ptr[s32]) s32 @public {
if pointer == nullptr {
return 0;
}
return (deref pointer);
}
fn main() s32 @public {
var number: s32 = 42;
return readOrZero(ref number);
}