pub struct AllocGuard<'a, T: ?Sized, A: BasicAlloc + ?Sized> { /* private fields */ }Expand description
A RAII guard that owns a single allocation and ensures it is deallocated unless explicitly released.
AllocGuard wraps a NonNull<T> pointer and an allocator reference &A. When
the guard goes out of scope, the underlying memory will be deallocated via the allocator.
To take ownership of the allocation without deallocating, call
release, which returns the raw pointer and prevents the guard
from running its cleanup.
This should be used in any situation where the initialization of a pointer’s data may panic. (e.g., initializing via a clone or any other user-implemented method)
§Examples
// Allocate space for one `u32` and wrap it in a guard
let layout = Layout::new::<u32>();
let mut guard = unsafe { AllocGuard::new(alloc.alloc(layout).unwrap().cast::<u32>(), &alloc) };
// Initialize the value
unsafe { guard.as_ptr().write(123) };
// If everything is OK, take ownership and prevent automatic deallocation
// (commented out for this example as the pointer won't be used)
// let raw = guard.release();Implementations§
Source§impl<'a, T: ?Sized, A: BasicAlloc + ?Sized> AllocGuard<'a, T, A>
impl<'a, T: ?Sized, A: BasicAlloc + ?Sized> AllocGuard<'a, T, A>
Sourcepub const unsafe fn new(ptr: NonNull<T>, alloc: &'a A) -> AllocGuard<'a, T, A>
pub const unsafe fn new(ptr: NonNull<T>, alloc: &'a A) -> AllocGuard<'a, T, A>
Creates a new guard from a pointer and a reference to an allocator.
Note that this is only const on Rust versions 1.61 and above.
§Safety
The caller must ensure ptr is a valid, readable, writable pointer allocated using
alloc.
Methods from Deref<Target = NonNull<T>>§
1.25.0 · Sourcepub unsafe fn as_ref<'a>(&self) -> &'a T
pub unsafe fn as_ref<'a>(&self) -> &'a T
Returns a shared reference to the value. If the value may be uninitialized, as_uninit_ref
must be used instead.
For the mutable counterpart see as_mut.
§Safety
When calling this method, you have to ensure that the pointer is convertible to a reference.
§Examples
use std::ptr::NonNull;
let mut x = 0u32;
let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
let ref_x = unsafe { ptr.as_ref() };
println!("{ref_x}");