Movatterモバイル変換


[0]ホーム

URL:


Module alloc

std

Modulealloc 

1.28.0 ·Source
Expand description

Memory allocation APIs.

In a given program, the standard library has one “global” memory allocatorthat is used for example byBox<T> andVec<T>.

Currently the default global allocator is unspecified. Libraries, however,likecdylibs andstaticlibs are guaranteed to use theSystem bydefault.

§The#[global_allocator] attribute

This attribute allows configuring the choice of global allocator.You can use this to implement a completely custom global allocatorto route all1 default allocation requests to a custom object.

usestd::alloc::{GlobalAlloc, System, Layout};structMyAllocator;unsafe implGlobalAllocforMyAllocator {unsafe fnalloc(&self, layout: Layout) ->*mutu8 {unsafe{ System.alloc(layout) }    }unsafe fndealloc(&self, ptr:*mutu8, layout: Layout) {unsafe{ System.dealloc(ptr, layout) }    }}#[global_allocator]staticGLOBAL: MyAllocator = MyAllocator;fnmain() {// This `Vec` will allocate memory through `GLOBAL` aboveletmutv = Vec::new();    v.push(1);}

The attribute is used on astatic item whose type implements theGlobalAlloc trait. This type can be provided by an external library:

usejemallocator::Jemalloc;#[global_allocator]staticGLOBAL: Jemalloc = Jemalloc;fnmain() {}

The#[global_allocator] can only be used once in a crateor its recursive dependencies.


  1. Note that the Rust standard library internals may stilldirectly callSystem when necessary (for example for the runtimesupport typically required to implement a global allocator, seere-entrance onGlobalAllocfor more details). 

Structs§

Layout
Layout of a block of memory.
LayoutError
TheLayoutError is returned when the parameters giventoLayout::from_size_alignor some otherLayout constructordo not satisfy its documented constraints.
System
The default memory allocator provided by the operating system.
AllocErrorExperimental
TheAllocError error indicates an allocation failurethat may be due to resource exhaustion or tosomething wrong when combining the given input arguments with thisallocator.
GlobalExperimental
The global memory allocator.

Traits§

GlobalAlloc
A memory allocator that can be registered as the standard library’s defaultthrough the#[global_allocator] attribute.
AllocatorExperimental
An implementation ofAllocator can allocate, grow, shrink, and deallocate arbitrary blocks ofdata described viaLayout.

Functions§

alloc
Allocates memory with the global allocator.
alloc_zeroed
Allocates zero-initialized memory with the global allocator.
dealloc
Deallocates memory with the global allocator.
handle_alloc_error
Signals a memory allocation error.
realloc
Reallocates memory with the global allocator.
set_alloc_error_hookExperimental
Registers a custom allocation error hook, replacing any that was previously registered.
take_alloc_error_hookExperimental
Unregisters the current allocation error hook, returning it.

Type Aliases§

LayoutErrDeprecated

[8]ページ先頭

©2009-2026 Movatter.jp