Skip to content

Commit 0c88dd6

Browse files
authored
Update Box::from_raw example to generalize better
I know very little about rust, so I saw this example and tried to generalize it by writing, ``` let layout = Layout::new::<T>(); let new_obj = unsafe { let ptr = alloc(layout) as *mut T; *ptr = obj; Box::from_raw(ptr) }; ``` for some more complicated `T`, which ended up crashing with SIGSEGV, because it tried to `drop_in_place` the previous object in `ptr` which is of course garbage. I also added a comment that explains why `.write` is used, but I think adding that comment is optional and may be too verbose here. I do however think that changing this example is a good idea to suggest the correct generalization. `.write` is also used in most of the rest of the documentation here, even if the example is `i32`, so it would additionally be more consistent.
1 parent 0c04344 commit 0c88dd6

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

src/liballoc/boxed.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,10 @@ impl<T: ?Sized> Box<T> {
382382
///
383383
/// unsafe {
384384
/// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
385-
/// *ptr = 5;
385+
/// // In general .write is required to avoid attempting to destruct
386+
/// // the (uninitialized) previous contents of `ptr`, though for this
387+
/// // simple example `*ptr = 5` would have worked as well.
388+
/// ptr.write(5);
386389
/// let x = Box::from_raw(ptr);
387390
/// }
388391
/// ```

0 commit comments

Comments
 (0)