diff options
| author | Mazdak <twingoow@gmail.com> | 2017-11-08 23:10:33 +0100 |
|---|---|---|
| committer | Mazdak <twingoow@gmail.com> | 2017-11-08 23:10:33 +0100 |
| commit | 360ce780fdae0dcb31cfa0f7ffa8a6c9fd62ed32 (patch) | |
| tree | c9e012f41277ea8ff785a6b05b992c11309eec48 /src | |
| parent | 7ca430df713ad1697a9d27eb4ae0f49c8563eed4 (diff) | |
| download | rust-360ce780fdae0dcb31cfa0f7ffa8a6c9fd62ed32.tar.gz rust-360ce780fdae0dcb31cfa0f7ffa8a6c9fd62ed32.zip | |
added associated function Box::leak
Diffstat (limited to 'src')
| -rw-r--r-- | src/liballoc/boxed.rs | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 79292d390e5..bcf0505ee82 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -364,6 +364,47 @@ impl<T: ?Sized> Box<T> { pub fn into_unique(b: Box<T>) -> Unique<T> { unsafe { mem::transmute(b) } } + + /// Consumes and leaks the `Box`, returning a static reference, + /// `&'static T`. + /// + /// This function is mainly useful for data that lives for the remainder of + /// the programs life. Dropping the returned reference will cause a memory + /// leak. If this is not acceptable, the reference should first be wrapped + /// with the [`Box::from_raw`] function producing a `Box` which can then be + /// dropped which will properly destroy `T` and release the memory. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Box::leak(b)` instead of `b.leak()`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// [`Box::from_raw`]: struct.Box.html#method.from_raw + /// + /// # Examples + /// + /// Simple usage: + /// + /// ``` + /// let x = Box::new(41); + /// let static_ref = Box::leak(x); + /// *static_ref += 1; + /// assert_eq!(*static_ref, 42); + /// ``` + /// + /// Unsized data: + /// + /// ``` + /// let x = vec![1, 2, 3].into_boxed_slice(); + /// let static_ref = Box::leak(x); + /// static_ref[0] = 4; + /// assert_eq!(*static_ref, [4, 2, 3]); + /// ``` + #[unstable(feature = "box_leak", reason = "needs an FCP to stabilize", + issue = "0")] + #[inline] + pub fn leak(b: Box<T>) -> &'static mut T { + unsafe { &mut *Box::into_raw(b) } + } } #[stable(feature = "rust1", since = "1.0.0")] |
