6

Box in std::boxed - Rust

 2 years ago
source link: https://doc.rust-lang.org/stable/std/boxed/struct.Box.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Implementations

Allocates memory on the heap and then places x into it.

This doesn’t actually allocate if T is zero-sized.

Examples
let five = Box::new(5);
Run
🔬 This is a nightly-only experimental API. (new_uninit #63291)

Constructs a new box with uninitialized contents.

Examples
#![feature(new_uninit)]

let mut five = Box::<u32>::new_uninit();

let five = unsafe {
    // Deferred initialization:
    five.as_mut_ptr().write(5);

    five.assume_init()
};

assert_eq!(*five, 5)
Run
🔬 This is a nightly-only experimental API. (new_uninit #63291)

Constructs a new Box with uninitialized contents, with the memory being filled with 0 bytes.

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

Examples
#![feature(new_uninit)]

let zero = Box::<u32>::new_zeroed();
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0)
Run
1.33.0 · source

pub fn pin(x: T) -> Pin<Box<T, Global>>ⓘ

Constructs a new Pin<Box<T>>. If T does not implement Unpin, then x will be pinned in memory and unable to be moved.

Constructing and pinning of the Box can also be done in two steps: Box::pin(x) does the same as Box::into_pin(Box::new(x)). Consider using into_pin if you already have a Box<T>, or if you want to construct a (pinned) Box in a different way than with Box::new.

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

Allocates memory on the heap then places x into it, returning an error if the allocation fails

This doesn’t actually allocate if T is zero-sized.

Examples
#![feature(allocator_api)]

let five = Box::try_new(5)?;
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new box with uninitialized contents on the heap, returning an error if the allocation fails

Examples
#![feature(allocator_api, new_uninit)]

let mut five = Box::<u32>::try_new_uninit()?;

let five = unsafe {
    // Deferred initialization:
    five.as_mut_ptr().write(5);

    five.assume_init()
};

assert_eq!(*five, 5);
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new Box with uninitialized contents, with the memory being filled with 0 bytes on the heap

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

Examples
#![feature(allocator_api, new_uninit)]

let zero = Box::<u32>::try_new_zeroed()?;
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0);
Run

source

impl<T, A> Box<T, A> where
    A: Allocator

const: unstable · source

pub fn new_in(x: T, alloc: A) -> Box<T, A>ⓘ where
    A: Allocator

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

Allocates memory in the given allocator then places x into it.

This doesn’t actually allocate if T is zero-sized.

Examples
#![feature(allocator_api)]

use std::alloc::System;

let five = Box::new_in(5, System);
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Allocates memory in the given allocator then places x into it, returning an error if the allocation fails

This doesn’t actually allocate if T is zero-sized.

Examples
#![feature(allocator_api)]

use std::alloc::System;

let five = Box::try_new_in(5, System)?;
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new box with uninitialized contents in the provided allocator.

Examples
#![feature(allocator_api, new_uninit)]

use std::alloc::System;

let mut five = Box::<u32, _>::new_uninit_in(System);

let five = unsafe {
    // Deferred initialization:
    five.as_mut_ptr().write(5);

    five.assume_init()
};

assert_eq!(*five, 5)
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new box with uninitialized contents in the provided allocator, returning an error if the allocation fails

Examples
#![feature(allocator_api, new_uninit)]

use std::alloc::System;

let mut five = Box::<u32, _>::try_new_uninit_in(System)?;

let five = unsafe {
    // Deferred initialization:
    five.as_mut_ptr().write(5);

    five.assume_init()
};

assert_eq!(*five, 5);
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new Box with uninitialized contents, with the memory being filled with 0 bytes in the provided allocator.

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

Examples
#![feature(allocator_api, new_uninit)]

use std::alloc::System;

let zero = Box::<u32, _>::new_zeroed_in(System);
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0)
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new Box with uninitialized contents, with the memory being filled with 0 bytes in the provided allocator, returning an error if the allocation fails,

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

Examples
#![feature(allocator_api, new_uninit)]

use std::alloc::System;

let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0);
Run
const: unstable · source

pub fn pin_in(x: T, alloc: A) -> Pin<Box<T, A>>ⓘ where
    A: 'static + Allocator

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

Constructs a new Pin<Box<T, A>>. If T does not implement Unpin, then x will be pinned in memory and unable to be moved.

Constructing and pinning of the Box can also be done in two steps: Box::pin_in(x, alloc) does the same as Box::into_pin(Box::new_in(x, alloc)). Consider using into_pin if you already have a Box<T, A>, or if you want to construct a (pinned) Box in a different way than with Box::new_in.

🔬 This is a nightly-only experimental API. (box_into_boxed_slice #71582)

Converts a Box<T> into a Box<[T]>

This conversion does not allocate on the heap and happens in place.

const: unstable · source

pub fn into_inner(boxed: Box<T, A>) -> T

🔬 This is a nightly-only experimental API. (box_into_inner #80437)

Consumes the Box, returning the wrapped value.

Examples
#![feature(box_into_inner)]

let c = Box::new(5);

assert_eq!(Box::into_inner(c), 5);
Run
🔬 This is a nightly-only experimental API. (new_uninit #63291)

Constructs a new boxed slice with uninitialized contents.

Examples
#![feature(new_uninit)]

let mut values = Box::<[u32]>::new_uninit_slice(3);

let values = unsafe {
    // Deferred initialization:
    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])
Run
🔬 This is a nightly-only experimental API. (new_uninit #63291)

Constructs a new boxed slice with uninitialized contents, with the memory being filled with 0 bytes.

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

Examples
#![feature(new_uninit)]

let values = Box::<[u32]>::new_zeroed_slice(3);
let values = unsafe { values.assume_init() };

assert_eq!(*values, [0, 0, 0])
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new boxed slice with uninitialized contents. Returns an error if the allocation fails

Examples
#![feature(allocator_api, new_uninit)]

let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
let values = unsafe {
    // Deferred initialization:
    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]);
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new boxed slice with uninitialized contents, with the memory being filled with 0 bytes. Returns an error if the allocation fails

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

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]);
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new boxed slice with uninitialized contents in the provided allocator.

Examples
#![feature(allocator_api, new_uninit)]

use std::alloc::System;

let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);

let values = unsafe {
    // Deferred initialization:
    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])
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Constructs a new boxed slice with uninitialized contents in the provided allocator, with the memory being filled with 0 bytes.

See MaybeUninit::zeroed for examples of correct and incorrect usage of this method.

Examples
#![feature(allocator_api, new_uninit)]

use std::alloc::System;

let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
let values = unsafe { values.assume_init() };

assert_eq!(*values, [0, 0, 0])
Run
const: unstable · source

pub unsafe fn assume_init(self) -> Box<T, A>ⓘ

🔬 This is a nightly-only experimental API. (new_uninit #63291)

Converts to Box<T, A>.

Safety

As with MaybeUninit::assume_init, it is up to the caller to guarantee that the value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

Examples
#![feature(new_uninit)]

let mut five = Box::<u32>::new_uninit();

let five: Box<u32> = unsafe {
    // Deferred initialization:
    five.as_mut_ptr().write(5);

    five.assume_init()
};

assert_eq!(*five, 5)
Run
const: unstable · source

pub fn write(boxed: Box<MaybeUninit<T>, A>, value: T) -> Box<T, A>ⓘ

🔬 This is a nightly-only experimental API. (new_uninit #63291)

Writes the value and converts to Box<T, A>.

This method converts the box similarly to Box::assume_init but writes value into it before conversion thus guaranteeing safety. In some scenarios use of this method may improve performance because the compiler may be able to optimize copying from stack.

Examples
#![feature(new_uninit)]

let big_box = Box::<[usize; 1024]>::new_uninit();

let mut array = [0; 1024];
for (i, place) in array.iter_mut().enumerate() {
    *place = i;
}

// The optimizer may be able to elide this copy, so previous code writes
// to heap directly.
let big_box = Box::write(big_box, array);

for (i, x) in big_box.iter().enumerate() {
    assert_eq!(*x, i);
}
Run
source

pub unsafe fn assume_init(self) -> Box<[T], A>ⓘ

🔬 This is a nightly-only experimental API. (new_uninit #63291)

Converts to Box<[T], A>.

Safety

As with MaybeUninit::assume_init, it is up to the caller to guarantee that the values really are in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

Examples
#![feature(new_uninit)]

let mut values = Box::<[u32]>::new_uninit_slice(3);

let values = unsafe {
    // Deferred initialization:
    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])
Run
1.4.0 · source

pub unsafe fn from_raw(raw: *mut T) -> Box<T, Global>ⓘ

Constructs a box from a raw pointer.

After calling this function, the raw pointer is owned by the resulting Box. Specifically, the Box destructor will call the destructor of T and free the allocated memory. For this to be safe, the memory must have been allocated in accordance with the memory layout used by Box .

Safety

This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same raw pointer.

The safety conditions are described in the memory layout section.

Examples

Recreate a Box which was previously converted to a raw pointer using Box::into_raw:

let x = Box::new(5);
let ptr = Box::into_raw(x);
let x = unsafe { Box::from_raw(ptr) };
Run

Manually create a Box from scratch by using the global allocator:

use std::alloc::{alloc, Layout};

unsafe {
    let ptr = alloc(Layout::new::<i32>()) as *mut i32;
    // In general .write is required to avoid attempting to destruct
    // the (uninitialized) previous contents of `ptr`, though for this
    // simple example `*ptr = 5` would have worked as well.
    ptr.write(5);
    let x = Box::from_raw(ptr);
}
Run

source

impl<T, A> Box<T, A> where
    A: Allocator,
    T: ?Sized

const: unstable · source

pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Box<T, A>ⓘ

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

Constructs a box from a raw pointer in the given allocator.

After calling this function, the raw pointer is owned by the resulting Box. Specifically, the Box destructor will call the destructor of T and free the allocated memory. For this to be safe, the memory must have been allocated in accordance with the memory layout used by Box .

Safety

This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same raw pointer.

Examples

Recreate a Box which was previously converted to a raw pointer using Box::into_raw_with_allocator:

#![feature(allocator_api)]

use std::alloc::System;

let x = Box::new_in(5, System);
let (ptr, alloc) = Box::into_raw_with_allocator(x);
let x = unsafe { Box::from_raw_in(ptr, alloc) };
Run

Manually create a Box from scratch by using the system allocator:

#![feature(allocator_api, slice_ptr_get)]

use std::alloc::{Allocator, Layout, System};

unsafe {
    let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
    // In general .write is required to avoid attempting to destruct
    // the (uninitialized) previous contents of `ptr`, though for this
    // simple example `*ptr = 5` would have worked as well.
    ptr.write(5);
    let x = Box::from_raw_in(ptr, System);
}
Run

Consumes the Box, returning a wrapped raw pointer.

The pointer will be properly aligned and non-null.

After calling this function, the caller is responsible for the memory previously managed by the Box. In particular, the caller should properly destroy T and release the memory, taking into account the memory layout used by Box. The easiest way to do this is to convert the raw pointer back into a Box with the Box::from_raw function, allowing the Box destructor to perform the cleanup.

Note: this is an associated function, which means that you have to call it as Box::into_raw(b) instead of b.into_raw(). This is so that there is no conflict with a method on the inner type.

Examples

Converting the raw pointer back into a Box with Box::from_raw for automatic cleanup:

let x = Box::new(String::from("Hello"));
let ptr = Box::into_raw(x);
let x = unsafe { Box::from_raw(ptr) };
Run

Manual cleanup by explicitly running the destructor and deallocating the memory:

use std::alloc::{dealloc, Layout};
use std::ptr;

let x = Box::new(String::from("Hello"));
let p = Box::into_raw(x);
unsafe {
    ptr::drop_in_place(p);
    dealloc(p as *mut u8, Layout::new::<String>());
}
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Consumes the Box, returning a wrapped raw pointer and the allocator.

The pointer will be properly aligned and non-null.

After calling this function, the caller is responsible for the memory previously managed by the Box. In particular, the caller should properly destroy T and release the memory, taking into account the memory layout used by Box. The easiest way to do this is to convert the raw pointer back into a Box with the Box::from_raw_in function, allowing the Box destructor to perform the cleanup.

Note: this is an associated function, which means that you have to call it as Box::into_raw_with_allocator(b) instead of b.into_raw_with_allocator(). This is so that there is no conflict with a method on the inner type.

Examples

Converting the raw pointer back into a Box with Box::from_raw_in for automatic cleanup:

#![feature(allocator_api)]

use std::alloc::System;

let x = Box::new_in(String::from("Hello"), System);
let (ptr, alloc) = Box::into_raw_with_allocator(x);
let x = unsafe { Box::from_raw_in(ptr, alloc) };
Run

Manual cleanup by explicitly running the destructor and deallocating the memory:

#![feature(allocator_api)]

use std::alloc::{Allocator, Layout, System};
use std::ptr::{self, NonNull};

let x = Box::new_in(String::from("Hello"), System);
let (ptr, alloc) = Box::into_raw_with_allocator(x);
unsafe {
    ptr::drop_in_place(ptr);
    let non_null = NonNull::new_unchecked(ptr);
    alloc.deallocate(non_null.cast(), Layout::new::<String>());
}
Run
🔬 This is a nightly-only experimental API. (allocator_api #32838)

Returns a reference to the underlying allocator.

Note: this is an associated function, which means that you have to call it as Box::allocator(&b) instead of b.allocator(). This is so that there is no conflict with a method on the inner type.

1.26.0 (const: unstable) · source

pub fn leak<'a>(b: Box<T, A>) -> &'a mut T where
    A: 'a, 

Consumes and leaks the Box, returning a mutable reference, &'a mut T. Note that the type T must outlive the chosen lifetime 'a. If the type has only static references, or none at all, then this may be chosen to be 'static.

This function is mainly useful for data that lives for the remainder of the program’s life. Dropping the returned reference will cause a memory leak. If this is not acceptable, the reference should first be wrapped with the Box::from_raw function producing a Box. This Box can then be dropped which will properly destroy T and release the allocated memory.

Note: this is an associated function, which means that you have to call it as Box::leak(b) instead of b.leak(). This is so that there is no conflict with a method on the inner type.

Examples

Simple usage:

let x = Box::new(41);
let static_ref: &'static mut usize = Box::leak(x);
*static_ref += 1;
assert_eq!(*static_ref, 42);
Run

Unsized data:

let x = vec![1, 2, 3].into_boxed_slice();
let static_ref = Box::leak(x);
static_ref[0] = 4;
assert_eq!(*static_ref, [4, 2, 3]);
Run
1.63.0 (const: unstable) · source

pub fn into_pin(boxed: Box<T, A>) -> Pin<Box<T, A>>ⓘ where
    A: 'static, 

Converts a Box<T> into a Pin<Box<T>>. If T does not implement Unpin, then *boxed will be pinned in memory and unable to be moved.

This conversion does not allocate on the heap and happens in place.

This is also available via From.

Constructing and pinning a Box with Box::into_pin(Box::new(x)) can also be written more concisely using Box::pin(x). This into_pin method is useful if you already have a Box<T>, or you are constructing a (pinned) Box in a different way than with Box::new.

Notes

It’s not recommended that crates add an impl like From<Box<T>> for Pin<T>, as it’ll introduce an ambiguity when calling Pin::from. A demonstration of such a poor impl is shown below.

struct Foo; // A type defined in this crate.
impl From<Box<()>> for Pin<Foo> {
    fn from(_: Box<()>) -> Pin<Foo> {
        Pin::new(Foo)
    }
}

let foo = Box::new(());
let bar = Pin::from(foo);
Run

source

impl<A> Box<dyn Any + 'static, A> where
    A: Allocator

source

pub fn downcast<T>(self) -> Result<Box<T, A>, Box<dyn Any + 'static, A>> where
    T: Any

Attempt to downcast the box to a concrete type.

Examples
use std::any::Any;

fn print_if_string(value: Box<dyn Any>) {
    if let Ok(string) = value.downcast::<String>() {
        println!("String ({}): {}", string.len(), string);
    }
}

let my_string = "Hello World".to_string();
print_if_string(Box::new(my_string));
print_if_string(Box::new(0i8));
Run
source

pub unsafe fn downcast_unchecked<T>(self) -> Box<T, A>ⓘ where
    T: Any

🔬 This is a nightly-only experimental API. (downcast_unchecked #90850)

Downcasts the box to a concrete type.

For a safe alternative see downcast.

Examples
#![feature(downcast_unchecked)]

use std::any::Any;

let x: Box<dyn Any> = Box::new(1_usize);

unsafe {
    assert_eq!(*x.downcast_unchecked::<usize>(), 1);
}
Run
Safety

The contained value must be of type T. Calling this method with the incorrect type is undefined behavior.

source

impl<A> Box<dyn Any + Send + 'static, A> where
    A: Allocator

source

pub fn downcast<T>(self) -> Result<Box<T, A>, Box<dyn Any + Send + 'static, A>> where
    T: Any

Attempt to downcast the box to a concrete type.

Examples
use std::any::Any;

fn print_if_string(value: Box<dyn Any + Send>) {
    if let Ok(string) = value.downcast::<String>() {
        println!("String ({}): {}", string.len(), string);
    }
}

let my_string = "Hello World".to_string();
print_if_string(Box::new(my_string));
print_if_string(Box::new(0i8));
Run
source

pub unsafe fn downcast_unchecked<T>(self) -> Box<T, A>ⓘ where
    T: Any

🔬 This is a nightly-only experimental API. (downcast_unchecked #90850)

Downcasts the box to a concrete type.

For a safe alternative see downcast.

Examples
#![feature(downcast_unchecked)]

use std::any::Any;

let x: Box<dyn Any + Send> = Box::new(1_usize);

unsafe {
    assert_eq!(*x.downcast_unchecked::<usize>(), 1);
}
Run
Safety

The contained value must be of type T. Calling this method with the incorrect type is undefined behavior.

source

impl<A> Box<dyn Any + Sync + Send + 'static, A> where
    A: Allocator

1.51.0 · source

pub fn downcast<T>(
    self
) -> Result<Box<T, A>, Box<dyn Any + Sync + Send + 'static, A>> where
    T: Any

Attempt to downcast the box to a concrete type.

Examples
use std::any::Any;

fn print_if_string(value: Box<dyn Any + Send + Sync>) {
    if let Ok(string) = value.downcast::<String>() {
        println!("String ({}): {}", string.len(), string);
    }
}

let my_string = "Hello World".to_string();
print_if_string(Box::new(my_string));
print_if_string(Box::new(0i8));
Run
source

pub unsafe fn downcast_unchecked<T>(self) -> Box<T, A>ⓘ where
    T: Any

🔬 This is a nightly-only experimental API. (downcast_unchecked #90850)

Downcasts the box to a concrete type.

For a safe alternative see downcast.

Examples
#![feature(downcast_unchecked)]

use std::any::Any;

let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);

unsafe {
    assert_eq!(*x.downcast_unchecked::<usize>(), 1);
}
Run
Safety

The contained value must be of type T. Calling this method with the incorrect type is undefined behavior.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK