@@ -364,6 +364,47 @@ impl<T: ?Sized> Box<T> {
364
364
pub fn into_unique ( b : Box < T > ) -> Unique < T > {
365
365
unsafe { mem:: transmute ( b) }
366
366
}
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
+ }
367
408
}
368
409
369
410
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
0 commit comments