pub struct Global;
allocator_api
#32838)Expand description
全局内存分配器。
此类型通过将调用转发到用 #[global_allocator]
属性注册的分配器 (如果有的话) 或 std
crate 的默认值来实现 Allocator
trait。
Note: 尽管此类型不稳定,但是可以通过 alloc
中的 free 函数 访问其提供的功能。
Implementations§
source§impl<T> Box<T, Global>
impl<T> Box<T, Global>
sourcepub fn new_uninit() -> Box<MaybeUninit<T>, Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_uninit() -> Box<MaybeUninit<T>, Global>
new_uninit
#63291)sourcepub fn new_zeroed() -> Box<MaybeUninit<T>, Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_zeroed() -> Box<MaybeUninit<T>, Global>
new_uninit
#63291)创建一个具有未初始化内容的新 Box
,并用 0
字节填充内存。
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(new_uninit)]
let zero = Box::<u32>::new_zeroed();
let zero = unsafe { zero.assume_init() };
assert_eq!(*zero, 0)
Run1.33.0 · sourcepub fn pin(x: T) -> Pin<Box<T, Global>>
pub fn pin(x: T) -> Pin<Box<T, Global>>
创建一个新的 Pin<Box<T>>
。如果 T
没有实现 Unpin
,那么 x
将被固定在内存中并且无法移动。
Box
的构建和固定也可以分两步完成: Box::pin(x)
与 Box::into_pin(Box::new(x))
相同。
如果您已经有 Box<T>
,或者如果您想以与 Box::new
不同的方式构建 (pinned) Box
,请考虑使用 into_pin
。
sourcepub fn try_new(x: T) -> Result<Box<T, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new(x: T) -> Result<Box<T, Global>, AllocError>
allocator_api
#32838)sourcepub fn try_new_uninit() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_uninit() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
allocator_api
#32838)sourcepub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
allocator_api
#32838)创建一个具有未初始化内容的新 Box
,堆中的内存由 0
字节填充
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(allocator_api, new_uninit)]
let zero = Box::<u32>::try_new_zeroed()?;
let zero = unsafe { zero.assume_init() };
assert_eq!(*zero, 0);
Runsource§impl<T> Box<[T], Global>
impl<T> Box<[T], Global>
sourcepub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
new_uninit
#63291)sourcepub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
new_uninit
#63291)创建一个具有未初始化内容的新 boxed 切片,并用 0
字节填充内存。
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(new_uninit)]
let values = Box::<[u32]>::new_zeroed_slice(3);
let values = unsafe { values.assume_init() };
assert_eq!(*values, [0, 0, 0])
Runsourcepub fn try_new_uninit_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_uninit_slice( len: usize ) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
allocator_api
#32838)创建一个具有未初始化内容的新 boxed 切片。 如果分配失败,则返回一个错误
Examples
#![feature(allocator_api, new_uninit)]
let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
let values = unsafe {
// 延迟初始化:
values[0].as_mut_ptr().write(1);
values[1].as_mut_ptr().write(2);
values[2].as_mut_ptr().write(3);
values.assume_init()
};
assert_eq!(*values, [1, 2, 3]);
Runsourcepub fn try_new_zeroed_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_zeroed_slice( len: usize ) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
allocator_api
#32838)创建一个具有未初始化内容的新 boxed 切片,并用 0
字节填充内存。
如果分配失败,则返回一个错误
有关正确和不正确使用此方法的示例,请参见 MaybeUninit::zeroed
。
Examples
#![feature(allocator_api, new_uninit)]
let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
let values = unsafe { values.assume_init() };
assert_eq!(*values, [0, 0, 0]);
Runsource§impl<T> Box<T, Global>where
T: ?Sized,
impl<T> Box<T, Global>where T: ?Sized,
1.4.0 · sourcepub unsafe fn from_raw(raw: *mut T) -> Box<T, Global>
pub unsafe fn from_raw(raw: *mut T) -> Box<T, Global>
从裸指针构造一个 box。
调用此函数后,结果 Box
拥有裸指针。
具体来说,Box
析构函数将调用 T
的析构函数并释放分配的内存。
为了安全起见,必须根据 Box
所使用的 内存布局 分配内存。
Safety
此函数不安全,因为使用不当可能会导致内存问题。 例如,如果在同一裸指针上两次调用该函数,则可能会出现 double-free。
安全条件在 内存布局 部分中进行了描述。
Examples
重新创建以前使用 Box::into_raw
转换为裸指针的 Box
:
let x = Box::new(5);
let ptr = Box::into_raw(x);
let x = unsafe { Box::from_raw(ptr) };
Run使用二进制分配器从头开始手动创建 Box
:
use std::alloc::{alloc, Layout};
unsafe {
let ptr = alloc(Layout::new::<i32>()) as *mut i32;
// 通常,需要 .write 以避免尝试销毁 `ptr` 以前的内容,尽管对于这个简单的示例 `*ptr = 5` 也可以工作。
ptr.write(5);
let x = Box::from_raw(ptr);
}
RunTrait Implementations§
source§impl Allocator for Global
impl Allocator for Global
source§fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocator_api
#32838)source§fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocator_api
#32838)allocate
,但也确保返回的内存被零初始化。 Read moresource§unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
allocator_api
#32838)ptr
引用的内存。 Read moresource§unsafe fn grow(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout ) -> Result<NonNull<[u8]>, AllocError>
allocator_api
#32838)source§unsafe fn grow_zeroed(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout ) -> Result<NonNull<[u8]>, AllocError>
allocator_api
#32838)grow
,但也确保在返回新内容之前将其设置为零。 Read moresource§impl<S> AsyncIterator for Box<S, Global>where
S: AsyncIterator + Unpin + ?Sized,
impl<S> AsyncIterator for Box<S, Global>where S: AsyncIterator + Unpin + ?Sized,
§type Item = <S as AsyncIterator>::Item
type Item = <S as AsyncIterator>::Item
async_iterator
#79024)1.8.0 · source§impl<T> Error for Box<T, Global>where
T: Error,
impl<T> Error for Box<T, Global>where T: Error,
1.6.0 · source§impl From<&str> for Box<dyn Error + 'static, Global>
impl From<&str> for Box<dyn Error + 'static, Global>
1.0.0 · source§impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global>
impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global>
1.45.0 · source§impl From<Cow<'_, str>> for Box<str, Global>
impl From<Cow<'_, str>> for Box<str, Global>
source§fn from(cow: Cow<'_, str>) -> Box<str, Global>
fn from(cow: Cow<'_, str>) -> Box<str, Global>
将 Cow<'_, str>
转换为 Box<str>
当 cow
是 Cow::Borrowed
变体时,此转换在堆上分配并复制底层 str
。
否则,它将尝试重用拥有所有权的 String
的分配。
Examples
use std::borrow::Cow;
let unboxed = Cow::Borrowed("hello");
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
Runlet unboxed = Cow::Owned("hello".to_string());
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
Run1.22.0 · source§impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global>
impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global>
1.22.0 · source§impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global>
impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global>
source§fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a, Global>
fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a, Global>
将 Cow
转换为 Dyn Error
+ Send
+ Sync
的 box。
Examples
use std::error::Error;
use std::mem;
use std::borrow::Cow;
let a_cow_str_error = Cow::from("a str error");
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run1.0.0 · source§impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where
E: Error + 'a,
impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where E: Error + 'a,
source§fn from(err: E) -> Box<dyn Error + 'a, Global>
fn from(err: E) -> Box<dyn Error + 'a, Global>
将 Error
的类型转换为 dyn Error
的 box。
Examples
use std::error::Error;
use std::fmt;
use std::mem;
#[derive(Debug)]
struct AnError;
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "An error")
}
}
impl Error for AnError {}
let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<dyn Error>::from(an_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Run1.0.0 · source§impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where
E: Error + Send + Sync + 'a,
impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where E: Error + Send + Sync + 'a,
source§fn from(err: E) -> Box<dyn Error + Send + Sync + 'a, Global>
fn from(err: E) -> Box<dyn Error + Send + Sync + 'a, Global>
将 Error
+ Send
+ Sync
的类型转换为 Dyn Error
+ Send
+ Sync
的 box。
Examples
use std::error::Error;
use std::fmt;
use std::mem;
#[derive(Debug)]
struct AnError;
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "An error")
}
}
impl Error for AnError {}
unsafe impl Send for AnError {}
unsafe impl Sync for AnError {}
let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run1.6.0 · source§impl From<String> for Box<dyn Error + 'static, Global>
impl From<String> for Box<dyn Error + 'static, Global>
1.0.0 · source§impl From<String> for Box<dyn Error + Send + Sync + 'static, Global>
impl From<String> for Box<dyn Error + Send + Sync + 'static, Global>
source§fn from(err: String) -> Box<dyn Error + Send + Sync + 'static, Global>
fn from(err: String) -> Box<dyn Error + Send + Sync + 'static, Global>
将 String
转换为 Dyn Error
+ Send
+ Sync
的 box。
Examples
use std::error::Error;
use std::mem;
let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run1.66.0 · source§impl<T, const N: usize> TryFrom<Vec<T, Global>> for Box<[T; N], Global>
impl<T, const N: usize> TryFrom<Vec<T, Global>> for Box<[T; N], Global>
source§fn try_from(
vec: Vec<T, Global>
) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Vec<T, Global>>>::Error>
fn try_from( vec: Vec<T, Global> ) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Vec<T, Global>>>::Error>
尝试将 Vec<T>
转换为 Box<[T; N]>
。
与 Vec::into_boxed_slice
一样,如果 vec.capacity() == N
是就地的,则需要重新分配。
Errors
如果 boxed_slice.len()
不等于 N
,则返回 Err
变体中的原始 Vec<T>
。
Examples
这可以与 vec!
一起用于在堆上创建一个数组:
let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
assert_eq!(state.len(), 100);
Run