Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
int
Rust
提交
a8d594f5
R
Rust
项目概览
int
/
Rust
大约 1 年 前同步成功
通知
1
Star
0
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
DevOps
流水线
流水线任务
计划
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
R
Rust
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
DevOps
DevOps
流水线
流水线任务
计划
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
流水线任务
提交
Issue看板
体验新版 GitCode,发现更多精彩内容 >>
提交
a8d594f5
编写于
9月 13, 2016
作者:
G
Guillaume Gomez
提交者:
GitHub
9月 13, 2016
浏览文件
操作
浏览文件
下载
差异文件
Rollup merge of #36357 - kmcallister:gh-29362-mem-docs, r=GuillaumeGomez
Tweak std::mem docs (#29362) r? @steveklabnik
上级
09905b11
72e103fe
变更
2
隐藏空白更改
内联
并排
Showing
2 changed file
with
231 addition
and
110 deletion
+231
-110
src/libcore/intrinsics.rs
src/libcore/intrinsics.rs
+30
-17
src/libcore/mem.rs
src/libcore/mem.rs
+201
-93
未找到文件。
src/libcore/intrinsics.rs
浏览文件 @
a8d594f5
...
...
@@ -262,22 +262,25 @@
/// Moves a value out of scope without running drop glue.
pub
fn
forget
<
T
>
(
_
:
T
)
->
();
/// Reinterprets the bits of a value of one type as another type; both types
/// must have the same size. Neither the original, nor the result, may be an
/// [invalid value] (../../nomicon/meet-safe-and-unsafe.html).
/// Reinterprets the bits of a value of one type as another type.
///
/// Both types must have the same size. Neither the original, nor the result,
/// may be an [invalid value](../../nomicon/meet-safe-and-unsafe.html).
///
/// `transmute` is semantically equivalent to a bitwise move of one type
/// into another. It copies the bits from the
destination typ
e into the
///
source type, then forgets the original. It's equivalent to C's `memcpy`
/// under the hood, just like `transmute_copy`.
/// into another. It copies the bits from the
source valu
e into the
///
destination value, then forgets the original. It's equivalent to C's
///
`memcpy`
under the hood, just like `transmute_copy`.
///
/// `transmute` is
incredibly
unsafe. There are a vast number of ways to
/// cause
undefined behavior
with this function. `transmute` should be
/// `transmute` is
**incredibly**
unsafe. There are a vast number of ways to
/// cause
[undefined behavior][ub]
with this function. `transmute` should be
/// the absolute last resort.
///
/// The [nomicon](../../nomicon/transmutes.html) has additional
/// documentation.
///
/// [ub]: ../../reference.html#behavior-considered-undefined
///
/// # Examples
///
/// There are a few things that `transmute` is really useful for.
...
...
@@ -292,7 +295,8 @@
/// assert_eq!(bitpattern, 0x3F800000);
/// ```
///
/// Turning a pointer into a function pointer:
/// Turning a pointer into a function pointer. This is *not* portable to
/// machines where function pointers and data pointers have different sizes.
///
/// ```
/// fn foo() -> i32 {
...
...
@@ -305,8 +309,8 @@
/// assert_eq!(function(), 0);
/// ```
///
/// Extending a lifetime, or shortening an invariant lifetime
; t
his is
/// advanced, very unsafe
rust:
/// Extending a lifetime, or shortening an invariant lifetime
. T
his is
/// advanced, very unsafe
Rust!
///
/// ```
/// struct R<'a>(&'a i32);
...
...
@@ -322,11 +326,9 @@
///
/// # Alternatives
///
/// However, many uses of `transmute` can be achieved through other means.
/// `transmute` can transform any type into any other, with just the caveat
/// that they're the same size, and often interesting results occur. Below
/// are common applications of `transmute` which can be replaced with safe
/// applications of `as`:
/// Don't despair: many uses of `transmute` can be achieved through other means.
/// Below are common applications of `transmute` which can be replaced with safer
/// constructs.
///
/// Turning a pointer into a `usize`:
///
...
...
@@ -335,6 +337,7 @@
/// let ptr_num_transmute = unsafe {
/// std::mem::transmute::<&i32, usize>(ptr)
/// };
///
/// // Use an `as` cast instead
/// let ptr_num_cast = ptr as *const i32 as usize;
/// ```
...
...
@@ -346,6 +349,7 @@
/// let ref_transmuted = unsafe {
/// std::mem::transmute::<*mut i32, &mut i32>(ptr)
/// };
///
/// // Use a reborrow instead
/// let ref_casted = unsafe { &mut *ptr };
/// ```
...
...
@@ -357,6 +361,7 @@
/// let val_transmuted = unsafe {
/// std::mem::transmute::<&mut i32, &mut u32>(ptr)
/// };
///
/// // Now, put together `as` and reborrowing - note the chaining of `as`
/// // `as` is not transitive
/// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) };
...
...
@@ -368,9 +373,11 @@
/// // this is not a good way to do this.
/// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") };
/// assert_eq!(slice, &[82, 117, 115, 116]);
///
/// // You could use `str::as_bytes`
/// let slice = "Rust".as_bytes();
/// assert_eq!(slice, &[82, 117, 115, 116]);
///
/// // Or, just use a byte string, if you have control over the string
/// // literal
/// assert_eq!(b"Rust", &[82, 117, 115, 116]);
...
...
@@ -381,18 +388,21 @@
/// ```
/// let store = [0, 1, 2, 3];
/// let mut v_orig = store.iter().collect::<Vec<&i32>>();
///
/// // Using transmute: this is Undefined Behavior, and a bad idea.
/// // However, it is no-copy.
/// let v_transmuted = unsafe {
/// std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(
/// v_orig.clone())
/// };
///
/// // This is the suggested, safe way.
/// // It does copy the entire
V
ector, though, into a new array.
/// // It does copy the entire
v
ector, though, into a new array.
/// let v_collected = v_orig.clone()
/// .into_iter()
/// .map(|r| Some(r))
/// .collect::<Vec<Option<&i32>>>();
///
/// // The no-copy, unsafe way, still using transmute, but not UB.
/// // This is equivalent to the original, but safer, and reuses the
/// // same Vec internals. Therefore the new inner type must have the
...
...
@@ -412,6 +422,7 @@
///
/// ```
/// use std::{slice, mem};
///
/// // There are multiple ways to do this; and there are multiple problems
/// // with the following, transmute, way.
/// fn split_at_mut_transmute<T>(slice: &mut [T], mid: usize)
...
...
@@ -426,6 +437,7 @@
/// (&mut slice[0..mid], &mut slice2[mid..len])
/// }
/// }
///
/// // This gets rid of the typesafety problems; `&mut *` will *only* give
/// // you an `&mut T` from an `&mut T` or `*mut T`.
/// fn split_at_mut_casts<T>(slice: &mut [T], mid: usize)
...
...
@@ -439,6 +451,7 @@
/// (&mut slice[0..mid], &mut slice2[mid..len])
/// }
/// }
///
/// // This is how the standard library does it. This is the best method, if
/// // you need to do something like this
/// fn split_at_stdlib<T>(slice: &mut [T], mid: usize)
...
...
src/libcore/mem.rs
浏览文件 @
a8d594f5
...
...
@@ -21,54 +21,39 @@
#[stable(feature
=
"rust1"
,
since
=
"1.0.0"
)]
pub
use
intrinsics
::
transmute
;
/// Leaks a value
into the void, consuming ownership and never running its
///
destructor
.
/// Leaks a value
: takes ownership and "forgets" about the value **without running
///
its destructor**
.
///
/// This function will take ownership of its argument, but is distinct from the
/// `mem::drop` function in that it **does not run the destructor**, leaking the
/// value and any resources that it owns.
/// Any resources the value manages, such as heap memory or a file handle, will linger
/// forever in an unreachable state.
///
/// There's only a few reasons to use this function. They mainly come
/// up in unsafe code or FFI code.
///
/// * You have an uninitialized value, perhaps for performance reasons, and
/// need to prevent the destructor from running on it.
/// * You have two copies of a value (like when writing something like
/// [`mem::swap`][swap]), but need the destructor to only run once to
/// prevent a double `free`.
/// * Transferring resources across [FFI][ffi] boundaries.
///
/// [swap]: fn.swap.html
/// [ffi]: ../../book/ffi.html
/// If you want to dispose of a value properly, running its destructor, see
/// [`mem::drop`][drop].
///
/// # Safety
///
/// This function is not marked as `unsafe` as Rust does not guarantee that the
/// `Drop` implementation for a value will always run. Note, however, that
/// leaking resources such as memory or I/O objects is likely not desired, so
/// this function is only recommended for specialized use cases.
///
/// The safety of this function implies that when writing `unsafe` code
/// yourself care must be taken when leveraging a destructor that is required to
/// run to preserve memory safety. There are known situations where the
/// destructor may not run (such as if ownership of the object with the
/// destructor is returned) which must be taken into account.
/// `forget` is not marked as `unsafe`, because Rust's safety guarantees
/// do not include a guarantee that destructors will always run. For example,
/// a program can create a reference cycle using [`Rc`][rc], or call
/// [`process:exit`][exit] to exit without running destructors. Thus, allowing
/// `mem::forget` from safe code does not fundamentally change Rust's safety
/// guarantees.
///
/// # Other forms of Leakage
/// That said, leaking resources such as memory or I/O objects is usually undesirable,
/// so `forget` is only recommended for specialized use cases like those shown below.
///
///
It's important to point out that this function is not the only method by
///
which a value can be leaked in safe Rust code. Other known sources of
///
leakage are:
///
Because forgetting a value is allowed, any `unsafe` code you write must
///
allow for this possibility. You cannot return a value and expect that the
///
caller will necessarily run the value's destructor.
///
/// * `Rc` and `Arc` cycles
/// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally)
/// * Panicking destructors are likely to leak local resources
/// [rc]: ../../std/rc/struct.Rc.html
/// [exit]: ../../std/process/fn.exit.html
///
/// # Example
/// # Example
s
///
/// Leak some heap memory by never deallocating it:
///
/// ```
rust
/// ```
/// use std::mem;
///
/// let heap_memory = Box::new(3);
...
...
@@ -77,7 +62,7 @@
///
/// Leak an I/O object, never closing the file:
///
/// ```
rust,
no_run
/// ```no_run
/// use std::mem;
/// use std::fs::File;
///
...
...
@@ -85,9 +70,43 @@
/// mem::forget(file);
/// ```
///
/// The `mem::swap` function uses `mem::forget` to good effect:
/// The practical use cases for `forget` are rather specialized and mainly come
/// up in unsafe or FFI code.
///
/// ## Use case 1
///
/// You have created an uninitialized value using [`mem::uninitialized`][uninit].
/// You must either initialize or `forget` it on every computation path before
/// Rust drops it automatically, like at the end of a scope or after a panic.
/// Running the destructor on an uninitialized value would be [undefined behavior][ub].
///
/// ```
/// use std::mem;
/// use std::ptr;
///
/// # let some_condition = false;
/// unsafe {
/// let mut uninit_vec: Vec<u32> = mem::uninitialized();
///
/// if some_condition {
/// // Initialize the variable.
/// ptr::write(&mut uninit_vec, Vec::new());
/// } else {
/// // Forget the uninitialized value so its destructor doesn't run.
/// mem::forget(uninit_vec);
/// }
/// }
/// ```
///
/// ## Use case 2
///
/// You have duplicated the bytes making up a value, without doing a proper
/// [`Clone`][clone]. You need the value's destructor to run only once,
/// because a double `free` is undefined behavior.
///
/// ```rust
/// An example is the definition of [`mem::swap`][swap] in this module:
///
/// ```
/// use std::mem;
/// use std::ptr;
///
...
...
@@ -109,6 +128,41 @@
/// }
/// }
/// ```
///
/// ## Use case 3
///
/// You are transferring ownership across a [FFI] boundary to code written in
/// another language. You need to `forget` the value on the Rust side because Rust
/// code is no longer responsible for it.
///
/// ```no_run
/// use std::mem;
///
/// extern "C" {
/// fn my_c_function(x: *const u32);
/// }
///
/// let x: Box<u32> = Box::new(3);
///
/// // Transfer ownership into C code.
/// unsafe {
/// my_c_function(&*x);
/// }
/// mem::forget(x);
/// ```
///
/// In this case, C code must call back into Rust to free the object. Calling C's `free`
/// function on a [`Box`][box] is *not* safe! Also, `Box` provides an [`into_raw`][into_raw]
/// method which is the preferred way to do this in practice.
///
/// [drop]: fn.drop.html
/// [uninit]: fn.uninitialized.html
/// [clone]: ../clone/trait.Clone.html
/// [swap]: fn.swap.html
/// [FFI]: ../../book/ffi.html
/// [box]: ../../std/boxed/struct.Box.html
/// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
/// [ub]: ../../reference.html#behavior-considered-undefined
#[inline]
#[stable(feature
=
"rust1"
,
since
=
"1.0.0"
)]
pub
fn
forget
<
T
>
(
t
:
T
)
{
...
...
@@ -133,7 +187,14 @@ pub fn size_of<T>() -> usize {
unsafe
{
intrinsics
::
size_of
::
<
T
>
()
}
}
/// Returns the size of the given value in bytes.
/// Returns the size of the pointed-to value in bytes.
///
/// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
/// statically known size, e.g. a slice [`[T]`][slice] or a [trait object],
/// then `size_of_val` can be used to get the dynamically-known size.
///
/// [slice]: ../../std/primitive.slice.html
/// [trait object]: ../../book/trait-objects.html
///
/// # Examples
///
...
...
@@ -141,6 +202,10 @@ pub fn size_of<T>() -> usize {
/// use std::mem;
///
/// assert_eq!(4, mem::size_of_val(&5i32));
///
/// let x: [u8; 13] = [0; 13];
/// let y: &[u8] = &x;
/// assert_eq!(13, mem::size_of_val(y));
/// ```
#[inline]
#[stable(feature
=
"rust1"
,
since
=
"1.0.0"
)]
...
...
@@ -148,10 +213,14 @@ pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
unsafe
{
intrinsics
::
size_of_val
(
val
)
}
}
/// Returns the ABI-required minimum alignment of a type
/// Returns the [ABI]-required minimum alignment of a type.
///
/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
/// ```
...
...
@@ -167,7 +236,11 @@ pub fn min_align_of<T>() -> usize {
unsafe
{
intrinsics
::
min_align_of
::
<
T
>
()
}
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
///
/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
...
...
@@ -184,10 +257,14 @@ pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
unsafe
{
intrinsics
::
min_align_of_val
(
val
)
}
}
/// Returns the alignment in memory for a type.
/// Returns the [ABI]-required minimum alignment of a type.
///
/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
/// ```
...
...
@@ -201,7 +278,11 @@ pub fn align_of<T>() -> usize {
unsafe
{
intrinsics
::
min_align_of
::
<
T
>
()
}
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
///
/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
...
...
@@ -216,16 +297,23 @@ pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
unsafe
{
intrinsics
::
min_align_of_val
(
val
)
}
}
/// Creates a value initialized to zero.
/// Creates a value whose bytes are all zero.
///
/// This has the same effect as allocating space with
/// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
/// [FFI] sometimes, but should generally be avoided.
///
/// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
/// operation).
/// There is no guarantee that an all-zero byte-pattern represents a valid value of
/// some type `T`. If `T` has a destructor and the value is destroyed (due to
/// a panic or the end of a scope) before being initialized, then the destructor
/// will run on zeroed data, likely leading to [undefined behavior][ub].
///
/// Care must be taken when using this function, if the type `T` has a destructor and the value
/// falls out of scope (due to unwinding or returning) before being initialized, then the
/// destructor will run on zeroed data, likely leading to crashes.
/// See also the documentation for [`mem::uninitialized`][uninit], which has
/// many of the same caveats.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
/// [uninit]: fn.uninitialized.html
/// [FFI]: ../../book/ffi.html
/// [ub]: ../../reference.html#behavior-considered-undefined
///
/// # Examples
///
...
...
@@ -233,6 +321,7 @@ pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
/// use std::mem;
///
/// let x: i32 = unsafe { mem::zeroed() };
/// assert_eq!(0, x);
/// ```
#[inline]
#[stable(feature
=
"rust1"
,
since
=
"1.0.0"
)]
...
...
@@ -241,32 +330,38 @@ pub unsafe fn zeroed<T>() -> T {
}
/// Bypasses Rust's normal memory-initialization checks by pretending to
/// produce a value of type
T
, while doing nothing at all.
/// produce a value of type
`T`
, while doing nothing at all.
///
/// **This is incredibly dangerous, and should not be done lightly. Deeply
/// consider initializing your memory with a default value instead.**
///
/// This is useful for
FFI
functions and initializing arrays sometimes,
/// This is useful for
[FFI]
functions and initializing arrays sometimes,
/// but should generally be avoided.
///
///
# Undefined Behavior
///
[FFI]: ../../book/ffi.html
///
/// It is Undefined Behavior to read uninitialized memory. Even just an
/// # Undefined behavior
///
/// It is [undefined behavior][ub] to read uninitialized memory, even just an
/// uninitialized boolean. For instance, if you branch on the value of such
/// a boolean your program may take one, both, or neither of the branches.
/// a boolean
,
your program may take one, both, or neither of the branches.
///
/// Note that this often also includes *writing* to the uninitialized value.
/// Rust believes the value is initialized, and will therefore try to Drop
/// the uninitialized value and its fields if you try to overwrite the memory
/// in a normal manner. The only way to safely initialize an arbitrary
/// uninitialized value is with one of the `ptr` functions: `write`, `copy`, or
/// `copy_nonoverlapping`. This isn't necessary if `T` is a primitive
/// or otherwise only contains types that don't implement Drop.
/// Writing to the uninitialized value is similarly dangerous. Rust believes the
/// value is initialized, and will therefore try to [`Drop`][drop] the uninitialized
/// value and its fields if you try to overwrite it in a normal manner. The only way
/// to safely initialize an uninitialized value is with [`ptr::write`][write],
/// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
///
/// If th
is value *does* need some kind of Drop
, it must be initialized before
/// If th
e value does implement `Drop`
, it must be initialized before
/// it goes out of scope (and therefore would be dropped). Note that this
/// includes a `panic` occurring and unwinding the stack suddenly.
///
/// [ub]: ../../reference.html#behavior-considered-undefined
/// [write]: ../ptr/fn.write.html
/// [copy]: ../intrinsics/fn.copy.html
/// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
/// [drop]: ../ops/trait.Drop.html
///
/// # Examples
///
/// Here's how to safely initialize an array of `Vec`s.
...
...
@@ -309,8 +404,8 @@ pub unsafe fn zeroed<T>() -> T {
/// println!("{:?}", &data[0]);
/// ```
///
/// This example emphasizes exactly how delicate and dangerous
doing this is.
/// Note that the `vec!` macro *does* let you initialize every element with a
/// This example emphasizes exactly how delicate and dangerous
using `mem::uninitialized`
///
can be.
Note that the `vec!` macro *does* let you initialize every element with a
/// value that is only `Clone`, so the following is semantically equivalent and
/// vastly less dangerous, as long as you can live with an extra heap
/// allocation:
...
...
@@ -325,21 +420,20 @@ pub unsafe fn uninitialized<T>() -> T {
intrinsics
::
uninit
()
}
/// Swap the values at two mutable locations of the same type, without deinitializing or copying
/// either one.
/// Swaps the values at two mutable locations, without deinitializing either one.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let
x = &mut
5;
/// let
y = &mut
42;
/// let
mut x =
5;
/// let
mut y =
42;
///
/// mem::swap(
x,
y);
/// mem::swap(
&mut x, &mut
y);
///
/// assert_eq!(42,
*
x);
/// assert_eq!(5,
*
y);
/// assert_eq!(42, x);
/// assert_eq!(5, y);
/// ```
#[inline]
#[stable(feature
=
"rust1"
,
since
=
"1.0.0"
)]
...
...
@@ -361,10 +455,7 @@ pub fn swap<T>(x: &mut T, y: &mut T) {
}
/// Replaces the value at a mutable location with a new one, returning the old value, without
/// deinitializing or copying either one.
///
/// This is primarily used for transferring and swapping ownership of a value in a mutable
/// location.
/// deinitializing either one.
///
/// # Examples
///
...
...
@@ -373,15 +464,17 @@ pub fn swap<T>(x: &mut T, y: &mut T) {
/// ```
/// use std::mem;
///
/// let mut v: Vec<i32> =
Vec::new()
;
/// let mut v: Vec<i32> =
vec![1, 2]
;
///
/// mem::replace(&mut v, Vec::new());
/// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
/// assert_eq!(2, old_v.len());
/// assert_eq!(3, v.len());
/// ```
///
///
This function allows consumption of one field of a struct
by replacing it with another value.
///
The normal approach doesn't always work
:
///
`replace` allows consumption of a struct field
by replacing it with another value.
///
Without `replace` you can run into issues like these
:
///
/// ```
rust,
ignore
/// ```ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
...
...
@@ -401,6 +494,7 @@ pub fn swap<T>(x: &mut T, y: &mut T) {
/// ```
/// # #![allow(dead_code)]
/// use std::mem;
///
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
...
...
@@ -417,14 +511,25 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
/// Disposes of a value.
///
/// While this does call the argument's implementation of
`Drop`, it will not
/// release any borrows, as borrows are based on lexical scope.
/// While this does call the argument's implementation of
[`Drop`][drop],
///
it will not
release any borrows, as borrows are based on lexical scope.
///
/// This effectively does nothing for
/// [types which implement `Copy`](../../book/ownership.html#copy-types),
/// e.g. integers. Such values are copied and _then_ moved into the function,
/// so the value persists after this function call.
///
/// This function is not magic; it is literally defined as
///
/// ```
/// pub fn drop<T>(_x: T) { }
/// ```
///
/// Because `_x` is moved into the function, it is automatically dropped before
/// the function returns.
///
/// [drop]: ../ops/trait.Drop.html
///
/// # Examples
///
/// Basic usage:
...
...
@@ -461,8 +566,8 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
/// v.push(4); // no problems
/// ```
///
/// Since `RefCell` enforces the borrow rules at runtime, `drop
()
` can
///
seemingly release a borrow of one
:
/// Since `RefCell` enforces the borrow rules at runtime, `drop` can
///
release a `RefCell` borrow
:
///
/// ```
/// use std::cell::RefCell;
...
...
@@ -478,7 +583,7 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
/// println!("{}", *borrow);
/// ```
///
/// Integers and other types implementing `Copy` are unaffected by `drop
()`
/// Integers and other types implementing `Copy` are unaffected by `drop
`.
///
/// ```
/// #[derive(Copy, Clone)]
...
...
@@ -496,19 +601,22 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
#[stable(feature
=
"rust1"
,
since
=
"1.0.0"
)]
pub
fn
drop
<
T
>
(
_
x
:
T
)
{
}
/// Interprets `src` as
`&U`, and then reads `src` without moving the contained
/// value.
/// Interprets `src` as
having type `&U`, and then reads `src` without moving
///
the contained
value.
///
/// This function will unsafely assume the pointer `src` is valid for
///
`sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
///
will also unsafely create a copy of the contained value instead of moving
/// out of `src`.
///
[`size_of::<U>()`][size_of] bytes by transmuting `&T` to `&U` and then reading
///
the `&U`. It will also unsafely create a copy of the contained value instead of
///
moving
out of `src`.
///
/// It is not a compile-time error if `T` and `U` have different sizes, but it
/// is highly encouraged to only invoke this function where `T` and `U` have the
/// same size. This function triggers
undefined behavior
if `U` is larger than
/// same size. This function triggers
[undefined behavior][ub]
if `U` is larger than
/// `T`.
///
/// [ub]: ../../reference.html#behavior-considered-undefined
/// [size_of]: fn.size_of.html
///
/// # Examples
///
/// ```
...
...
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录