Skip to content

Commit dce8fab

Browse files
committed
Use ManuallyDrop in examples for {Vec,String}::from_raw_parts
1 parent 0d21d25 commit dce8fab

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

src/liballoc/string.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,10 @@ use crate::vec::Vec;
194194
/// ```
195195
/// use std::mem;
196196
///
197-
/// let mut story = String::from("Once upon a time...");
197+
/// let story = String::from("Once upon a time...");
198+
///
199+
/// // Prevent automatically dropping the String's data
200+
/// let mut story = mem::ManuallyDrop::new(story);
198201
///
199202
/// let ptr = story.as_mut_ptr();
200203
/// let len = story.len();
@@ -203,9 +206,6 @@ use crate::vec::Vec;
203206
/// // story has nineteen bytes
204207
/// assert_eq!(19, len);
205208
///
206-
/// // Now that we have our parts, we throw the story away.
207-
/// mem::forget(story);
208-
///
209209
/// // We can re-build a String out of ptr, len, and capacity. This is all
210210
/// // unsafe because we are responsible for making sure the components are
211211
/// // valid:
@@ -676,13 +676,15 @@ impl String {
676676
/// use std::mem;
677677
///
678678
/// unsafe {
679-
/// let mut s = String::from("hello");
679+
/// let s = String::from("hello");
680+
///
681+
/// // Prevent automatically dropping the String's data
682+
/// let mut s = mem::ManuallyDrop::new(s);
683+
///
680684
/// let ptr = s.as_mut_ptr();
681685
/// let len = s.len();
682686
/// let capacity = s.capacity();
683687
///
684-
/// mem::forget(s);
685-
///
686688
/// let s = String::from_raw_parts(ptr, len, capacity);
687689
///
688690
/// assert_eq!(String::from("hello"), s);

src/liballoc/vec.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -389,18 +389,18 @@ impl<T> Vec<T> {
389389
/// use std::ptr;
390390
/// use std::mem;
391391
///
392-
/// let mut v = vec![1, 2, 3];
392+
/// let v = vec![1, 2, 3];
393+
///
394+
/// // Prevent running `v`'s destructor so we are in complete control
395+
/// // of the allocation.
396+
/// let mut v = mem::ManuallyDrop::new(v);
393397
///
394398
/// // Pull out the various important pieces of information about `v`
395399
/// let p = v.as_mut_ptr();
396400
/// let len = v.len();
397401
/// let cap = v.capacity();
398402
///
399403
/// unsafe {
400-
/// // Cast `v` into the void: no destructor run, so we are in
401-
/// // complete control of the allocation to which `p` points.
402-
/// mem::forget(v);
403-
///
404404
/// // Overwrite memory with 4, 5, 6
405405
/// for i in 0..len as isize {
406406
/// ptr::write(p.offset(i), 4 + i);

0 commit comments

Comments
 (0)