Skip to content

Commit 360ce78

Browse files
committed
added associated function Box::leak
1 parent 7ca430d commit 360ce78

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/liballoc/boxed.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,47 @@ impl<T: ?Sized> Box<T> {
364364
pub fn into_unique(b: Box<T>) -> Unique<T> {
365365
unsafe { mem::transmute(b) }
366366
}
367+
368+
/// Consumes and leaks the `Box`, returning a static reference,
369+
/// `&'static T`.
370+
///
371+
/// This function is mainly useful for data that lives for the remainder of
372+
/// the programs life. Dropping the returned reference will cause a memory
373+
/// leak. If this is not acceptable, the reference should first be wrapped
374+
/// with the [`Box::from_raw`] function producing a `Box` which can then be
375+
/// dropped which will properly destroy `T` and release the memory.
376+
///
377+
/// Note: this is an associated function, which means that you have
378+
/// to call it as `Box::leak(b)` instead of `b.leak()`. This
379+
/// is so that there is no conflict with a method on the inner type.
380+
///
381+
/// [`Box::from_raw`]: struct.Box.html#method.from_raw
382+
///
383+
/// # Examples
384+
///
385+
/// Simple usage:
386+
///
387+
/// ```
388+
/// let x = Box::new(41);
389+
/// let static_ref = Box::leak(x);
390+
/// *static_ref += 1;
391+
/// assert_eq!(*static_ref, 42);
392+
/// ```
393+
///
394+
/// Unsized data:
395+
///
396+
/// ```
397+
/// let x = vec![1, 2, 3].into_boxed_slice();
398+
/// let static_ref = Box::leak(x);
399+
/// static_ref[0] = 4;
400+
/// assert_eq!(*static_ref, [4, 2, 3]);
401+
/// ```
402+
#[unstable(feature = "box_leak", reason = "needs an FCP to stabilize",
403+
issue = "0")]
404+
#[inline]
405+
pub fn leak(b: Box<T>) -> &'static mut T {
406+
unsafe { &mut *Box::into_raw(b) }
407+
}
367408
}
368409

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

0 commit comments

Comments
 (0)