Skip to content

Commit b00c310

Browse files
committed
Rollup merge of rust-lang#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.
2 parents da054a5 + 5d9ed0b commit b00c310

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

src/libcore/ptr.rs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -33,31 +33,34 @@
3333
//! let my_speed_ptr: *mut i32 = &mut my_speed;
3434
//! ```
3535
//!
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+
//!
3645
//! This does not take ownership of the original allocation
3746
//! and requires no resource management later,
3847
//! but you must not use the pointer after its lifetime.
3948
//!
40-
//! ## 2. Transmute an owned box (`Box<T>`).
49+
//! ## 2. Consume a box (`Box<T>`).
4150
//!
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.
4753
//!
4854
//! ```
49-
//! use std::mem;
55+
//! use std::boxed;
5056
//!
5157
//! unsafe {
52-
//! let my_num: Box<i32> = Box::new(10);
53-
//! let my_num: *const i32 = mem::transmute(my_num);
5458
//! 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);
5660
//!
5761
//! // 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));
6164
//! }
6265
//! ```
6366
//!

0 commit comments

Comments
 (0)