diff options
| author | Manish Goregaokar <manishsmail@gmail.com> | 2020-07-01 07:42:42 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-07-01 07:42:42 -0700 |
| commit | 6556f269918124b43db67367867c6930cb3189c9 (patch) | |
| tree | 8233907da0a14d05eadcfab203ed663548888a6c /src/liballoc | |
| parent | 0eb9799695db2920e7cdebf7a8a8a9772365d4d1 (diff) | |
| parent | 0c88dd663a7095ccc405a2036047a90981137a51 (diff) | |
Rollup merge of #73678 - Keno:patch-1, r=LukasKalbertodt
Update Box::from_raw example to generalize better
I know very little about rust, so I saw the example here
```
use std::alloc::{alloc, Layout};
unsafe {
let ptr = alloc(Layout::new::<i32>()) as *mut i32;
*ptr = 5;
let x = Box::from_raw(ptr);
}
```
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 think that changing this example to use `.write` instead
would be a good idea to suggest the correct generalization. It is also more
consistent with other documentation items in this file, which use `.write`.
I also added a comment to explain it, but I'm not too attached to that,
and can see it being too verbose in this place.
Diffstat (limited to 'src/liballoc')
| -rw-r--r-- | src/liballoc/boxed.rs | 5 |
1 files changed, 4 insertions, 1 deletions
diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index f1b560b9b96..3320ebdf821 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -384,7 +384,10 @@ impl<T: ?Sized> Box<T> { /// /// unsafe { /// let ptr = alloc(Layout::new::<i32>()) as *mut i32; - /// *ptr = 5; + /// // In general .write is required to avoid attempting to destruct + /// // the (uninitialized) previous contents of `ptr`, though for this + /// // simple example `*ptr = 5` would have worked as well. + /// ptr.write(5); /// let x = Box::from_raw(ptr); /// } /// ``` |
