|
33 | 33 | //! let my_speed_ptr: *mut i32 = &mut my_speed;
|
34 | 34 | //! ```
|
35 | 35 | //!
|
| 36 | +//! To get a pointer to a boxed value, dereference the box: |
| 37 | +//! |
| 38 | +//! ``` |
| 39 | +//! let my_num: Box<i32> = Box::new(10); |
| 40 | +//! let my_num_ptr: *const i32 = &*my_num; |
| 41 | +//! let mut my_speed: Box<i32> = Box::new(88); |
| 42 | +//! let my_speed_ptr: *mut i32 = &mut *my_speed; |
| 43 | +//! ``` |
| 44 | +//! |
36 | 45 | //! This does not take ownership of the original allocation
|
37 | 46 | //! and requires no resource management later,
|
38 | 47 | //! but you must not use the pointer after its lifetime.
|
39 | 48 | //!
|
40 |
| -//! ## 2. Transmute an owned box (`Box<T>`). |
| 49 | +//! ## 2. Consume a box (`Box<T>`). |
41 | 50 | //!
|
42 |
| -//! The `transmute` function takes, by value, whatever it's given |
43 |
| -//! and returns it as whatever type is requested, as long as the |
44 |
| -//! types are the same size. Because `Box<T>` and `*mut T` have the same |
45 |
| -//! representation they can be trivially, |
46 |
| -//! though unsafely, transformed from one type to the other. |
| 51 | +//! The `into_raw` function consumes a box and returns |
| 52 | +//! the raw pointer. It doesn't destroy `T` or deallocate any memory. |
47 | 53 | //!
|
48 | 54 | //! ```
|
49 |
| -//! use std::mem; |
| 55 | +//! use std::boxed; |
50 | 56 | //!
|
51 | 57 | //! unsafe {
|
52 |
| -//! let my_num: Box<i32> = Box::new(10); |
53 |
| -//! let my_num: *const i32 = mem::transmute(my_num); |
54 | 58 | //! let my_speed: Box<i32> = Box::new(88);
|
55 |
| -//! let my_speed: *mut i32 = mem::transmute(my_speed); |
| 59 | +//! let my_speed: *mut i32 = boxed::into_raw(my_speed); |
56 | 60 | //!
|
57 | 61 | //! // By taking ownership of the original `Box<T>` though
|
58 |
| -//! // we are obligated to transmute it back later to be destroyed. |
59 |
| -//! drop(mem::transmute::<_, Box<i32>>(my_speed)); |
60 |
| -//! drop(mem::transmute::<_, Box<i32>>(my_num)); |
| 62 | +//! // we are obligated to put it together later to be destroyed. |
| 63 | +//! drop(Box::from_raw(my_speed)); |
61 | 64 | //! }
|
62 | 65 | //! ```
|
63 | 66 | //!
|
|
0 commit comments