diff options
| author | Manish Goregaokar <manishsmail@gmail.com> | 2015-03-13 18:11:34 +0530 |
|---|---|---|
| committer | Manish Goregaokar <manishsmail@gmail.com> | 2015-03-13 18:11:34 +0530 |
| commit | b00c310985d5ecd2439672ab595f81aaaf0a7382 (patch) | |
| tree | ab86a014b93863c6f80a60d25764e984df9a31f2 | |
| parent | da054a5f87cb857e0c1b8684d32bb04064b9aaf1 (diff) | |
| parent | 5d9ed0bc0e7922fb1fbdc518edc9bacb342fad6e (diff) | |
Rollup merge of #23312 - gkoz:ptr_from_box_docs, r=steveklabnik
Show how to get a pointer without destroying the box. Use `boxed::into_raw` instead of `mem::transmute`. I removed the `let my_num: *const i32 = mem::transmute(my_num);` case altogether because we own the box, a `*mut` pointer is good anywhere a `*const` is needed, `from_raw` takes a mutable pointer and casting from a `*const` caused an ICE.
| -rw-r--r-- | src/libcore/ptr.rs | 29 |
1 files changed, 16 insertions, 13 deletions
diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 0625c3c7d60..32123a8271c 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -33,31 +33,34 @@ //! let my_speed_ptr: *mut i32 = &mut my_speed; //! ``` //! +//! To get a pointer to a boxed value, dereference the box: +//! +//! ``` +//! let my_num: Box<i32> = Box::new(10); +//! let my_num_ptr: *const i32 = &*my_num; +//! let mut my_speed: Box<i32> = Box::new(88); +//! let my_speed_ptr: *mut i32 = &mut *my_speed; +//! ``` +//! //! This does not take ownership of the original allocation //! and requires no resource management later, //! but you must not use the pointer after its lifetime. //! -//! ## 2. Transmute an owned box (`Box<T>`). +//! ## 2. Consume a box (`Box<T>`). //! -//! The `transmute` function takes, by value, whatever it's given -//! and returns it as whatever type is requested, as long as the -//! types are the same size. Because `Box<T>` and `*mut T` have the same -//! representation they can be trivially, -//! though unsafely, transformed from one type to the other. +//! The `into_raw` function consumes a box and returns +//! the raw pointer. It doesn't destroy `T` or deallocate any memory. //! //! ``` -//! use std::mem; +//! use std::boxed; //! //! unsafe { -//! let my_num: Box<i32> = Box::new(10); -//! let my_num: *const i32 = mem::transmute(my_num); //! let my_speed: Box<i32> = Box::new(88); -//! let my_speed: *mut i32 = mem::transmute(my_speed); +//! let my_speed: *mut i32 = boxed::into_raw(my_speed); //! //! // By taking ownership of the original `Box<T>` though -//! // we are obligated to transmute it back later to be destroyed. -//! drop(mem::transmute::<_, Box<i32>>(my_speed)); -//! drop(mem::transmute::<_, Box<i32>>(my_num)); +//! // we are obligated to put it together later to be destroyed. +//! drop(Box::from_raw(my_speed)); //! } //! ``` //! |
