Skip to content

Commit 246a6d1

Browse files
committed
Auto merge of #45881 - Centril:box-leak, r=alexcrichton
Add Box::leak<'a>(Box<T>) -> &'a mut T where T: 'a Adds: ```rust impl<T: ?Sized> Box<T> { pub fn leak<'a>(b: Box<T>) -> &'a mut T where T: 'a { unsafe { &mut *Box::into_raw(b) } } } ``` which is useful for when you just want to put some stuff on the heap and then have a reference to it for the remainder of the program. r? @sfackler cc @durka
2 parents 0916bbc + bc18d99 commit 246a6d1

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

src/liballoc/boxed.rs

+53
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,59 @@ impl<T: ?Sized> Box<T> {
374374
unique
375375
};
376376
}
377+
378+
/// Consumes and leaks the `Box`, returning a mutable reference,
379+
/// `&'a mut T`. Here, the lifetime `'a` may be chosen to be `'static`.
380+
///
381+
/// This function is mainly useful for data that lives for the remainder of
382+
/// the program's life. Dropping the returned reference will cause a memory
383+
/// leak. If this is not acceptable, the reference should first be wrapped
384+
/// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
385+
/// then be dropped which will properly destroy `T` and release the
386+
/// allocated memory.
387+
///
388+
/// Note: this is an associated function, which means that you have
389+
/// to call it as `Box::leak(b)` instead of `b.leak()`. This
390+
/// is so that there is no conflict with a method on the inner type.
391+
///
392+
/// [`Box::from_raw`]: struct.Box.html#method.from_raw
393+
///
394+
/// # Examples
395+
///
396+
/// Simple usage:
397+
///
398+
/// ```
399+
/// #![feature(box_leak)]
400+
///
401+
/// fn main() {
402+
/// let x = Box::new(41);
403+
/// let static_ref: &'static mut usize = Box::leak(x);
404+
/// *static_ref += 1;
405+
/// assert_eq!(*static_ref, 42);
406+
/// }
407+
/// ```
408+
///
409+
/// Unsized data:
410+
///
411+
/// ```
412+
/// #![feature(box_leak)]
413+
///
414+
/// fn main() {
415+
/// let x = vec![1, 2, 3].into_boxed_slice();
416+
/// let static_ref = Box::leak(x);
417+
/// static_ref[0] = 4;
418+
/// assert_eq!(*static_ref, [4, 2, 3]);
419+
/// }
420+
/// ```
421+
#[unstable(feature = "box_leak", reason = "needs an FCP to stabilize",
422+
issue = "46179")]
423+
#[inline]
424+
pub fn leak<'a>(b: Box<T>) -> &'a mut T
425+
where
426+
T: 'a // Technically not needed, but kept to be explicit.
427+
{
428+
unsafe { &mut *Box::into_raw(b) }
429+
}
377430
}
378431

379432
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)