Trait GlobalAllocator

pub unsafe trait GlobalAllocator: StaticAllocator + Sync + 'static

An Allocator that can be registered as the standard library’s default through the #[global_allocator] attribute.

Types implementing this trait can be used as the default allocator for memory allocations through Box, Vec and the collection types. For instance, the System allocator implements this trait, and thus can be explicitly set as the default like so:

use std::alloc::System;

#[global_allocator]
static ALLOCATOR: System = System;

The Global allocator forwards all memory allocation requests to the static annotated with #[global_allocator]. Hence, Global does not implement GlobalAllocator itself, as that would lead to infinite recursion.

Note to implementors

This trait is used to prevent the infinite recursion that would occur if the default allocator were to attempt to allocate memory through Global (and thus from itself).

When to implement this trait:

When not to implement this trait:

Safety

When implementing a global allocator, one has to be careful not to create an infinitely recursive implementation by accident, as many constructs in the Rust standard library may allocate in their implementation. For example, on some platforms, std::sync::Mutex may allocate, so using it is highly problematic in a global allocator.

For this reason, one should generally stick to library features available through core, and avoid using std in a global allocator. A few features from std are guaranteed to not use #[global_allocator] to allocate: