expression
RAII for an owned opaque handle
An owning wrapper releases its handle once, even when control leaves early. This model uses Box to stand in for a native allocator; a real wrapper must call the matching native destructor. The private pointer is never cloned or exposed. Expected stdout (not executed): 8 Common mistake: Deriving Clone for an owning raw handle without a matching ownership protocol.
Formal Syntax & Structure
rust syntaxrust
NonNull<T> + DropWorking Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { use std::ptr::NonNull; struct Owned(NonNull<u32>); impl Owned { fn new(v: u32) -> Self { Self(NonNull::from(Box::leak(Box::new(v)))) } fn get(&self) -> u32 { // SAFETY: self owns the initialized allocation until Drop. unsafe { *self.0.as_ptr() } } } impl Drop for Owned { fn drop(&mut self) { // SAFETY: pointer originated from Box::leak; no other owner exists. unsafe { drop(Box::from_raw(self.0.as_ptr())); } } } let h = Owned::new(8); println!("{}", h.get());}