Skip to content
CryoCryo home
Stdliballoc

box

import std::alloc::box; — in the prelude · source

Box<T, A>

type struct Box<T, A = GlobalAlloc> {
    ptr:   T*;
    alloc: A;

    static new(value: T) -> Box<T, GlobalAlloc>;
    static new_in(value: T, alloc: A) -> Box<T, A>;
    static try_new(value: T) -> Result<Box<T, GlobalAlloc>, AllocError>;
    static try_new_in(value: T, alloc: A) -> Result<Box<T, A>, AllocError>;
    static from_raw(raw: T*) -> Box<T, GlobalAlloc>;
    as_ptr(&this) -> T*;
    get_ref(&this) -> T*;
    get_mut(mut &this) -> T*;
    into_raw(mut this) -> T*;
    leak(mut this) -> T*;
}

A Box owns exactly one heap value plus the allocator instance that produced it. Moves transfer ownership; the final holder's drop runs T::drop() and returns the storage.

mut b: Box<Config> = Box<Config>::new(config);
b.port = 8080;          // auto-deref through Deref<T>
MethodNotes
new(value)Allocates via GlobalAlloc. Panics on failure.
new_in(value, alloc)With your own allocator. Panics on failure.
try_new / try_new_inThe fallible forms.
get_ref / get_mutT* — borrow the value. A Box is a unique owner, so get_mut is always sound.
as_ptrT*, valid for the lifetime of the box.
into_rawT* — gives up ownership; you are now responsible for freeing it.
leakAlias for into_raw.
from_raw(raw)Re-wrap a pointer from into_raw. It must have come from a Box<T, GlobalAlloc>.

Note that into_raw and leak transfer both the value and the allocation, so T::drop() does not run on those paths.

Trait implementations

implement<T, A> trait Drop for struct Box<T, A>
where T: Drop, A: Allocator

implement<T> trait Clone for struct Box<T, GlobalAlloc>
where T: Clone

implement<T, A> trait Deref<T> for struct Box<T, A>

Deref<T> is what makes *b, b.field, and b.method() work directly on the box. Clone is a deep copy into fresh GlobalAlloc storage.