Struct std::alloc::System1.28.0[−][src]

pub struct System;
Expand description

操作系统提供的默认内存分配器。

它基于 Unix 平台上的 malloc 和 Windows 上的 HeapAlloc,以及相关的函数。

此类型默认情况下实现 GlobalAlloc trait 和 Rust 程序,就像它们具有以下定义一样:

use std::alloc::System;

#[global_allocator]
static A: System = System;

fn main() {
    let a = Box::new(4); // 从系统分配器分配。
    println!("{}", a);
}
Run

如果愿意,还可以围绕 System 定义自己的包装器,例如跟踪分配的所有字节数:

use std::alloc::{System, GlobalAlloc, Layout};
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};

struct Counter;

static ALLOCATED: AtomicUsize = AtomicUsize::new(0);

unsafe impl GlobalAlloc for Counter {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let ret = System.alloc(layout);
        if !ret.is_null() {
            ALLOCATED.fetch_add(layout.size(), SeqCst);
        }
        return ret
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        System.dealloc(ptr, layout);
        ALLOCATED.fetch_sub(layout.size(), SeqCst);
    }
}

#[global_allocator]
static A: Counter = Counter;

fn main() {
    println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
}
Run

它也可以直接用于独立于 Rust 程序选择的分配器来分配内存。 例如,如果 Rust 程序选择使用 jemalloc 作为分配器,则 System 仍将使用 malloc 和 HeapAlloc 分配内存。

Trait Implementations

🔬 This is a nightly-only experimental API. (allocator_api #32838)

尝试分配一块内存。 Read more

🔬 This is a nightly-only experimental API. (allocator_api #32838)

行为类似于 allocate,但也确保返回的内存被零初始化。 Read more

🔬 This is a nightly-only experimental API. (allocator_api #32838)

释放 ptr 引用的内存。 Read more

🔬 This is a nightly-only experimental API. (allocator_api #32838)

尝试扩展内存块。 Read more

🔬 This is a nightly-only experimental API. (allocator_api #32838)

行为类似于 grow,但也确保在返回新内容之前将其设置为零。 Read more

🔬 This is a nightly-only experimental API. (allocator_api #32838)

尝试缩小内存块。 Read more

🔬 This is a nightly-only experimental API. (allocator_api #32838)

为此 Allocator 实例创建 “by reference” 适配器。 Read more

返回值的副本。 Read more

从 source 执行复制分配。 Read more

使用给定的格式化程序格式化该值。 Read more

返回类型的 “default value”。 Read more

按照给定的 layout 分配内存。 Read more

行为类似于 alloc,但也确保在返回之前将内容设置为零。 Read more

使用给定的 layout 在给定的 ptr 指针处释放内存块。 Read more

将内存块缩小或增加到给定的 new_size。 该块由给定的 ptr 指针和 layout 描述。 Read more

Auto Trait Implementations

Blanket Implementations

获取 self 的 TypeId。 Read more

从拥有的值中一成不变地借用。 Read more

从拥有的值中借用。 Read more

执行转换。

执行转换。

获得所有权后的结果类型。

通常通过克隆从借用数据中创建拥有的数据。 Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into #41263)

recently added

使用借来的数据来替换拥有的数据,通常是通过克隆。 Read more

发生转换错误时返回的类型。

执行转换。

发生转换错误时返回的类型。

执行转换。