`std::Mem::swap`是如何工作的? [英] How does `std::mem::swap` work?
本文介绍了`std::Mem::swap`是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
交换同一类型的两个可变位置上的值,而不取消初始化或复制其中任何一个。use std::mem; let x = &mut 5; let y = &mut 42; mem::swap(x, y); assert_eq!(42, *x); assert_eq!(5, *y);
(出自offical Rust doc)
如何在不复制的情况下交换两个值?值42
是如何从y
变为x
的?这应该是不可能的。
推荐答案
该函数实际上在内部创建副本:以下是从文档中摘录的源代码:
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninitialized();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping(&*x, &mut t, 1);
ptr::copy_nonoverlapping(&*y, x, 1);
ptr::copy_nonoverlapping(&t, y, 1);
// y and t now point to the same thing,
// but we need to completely forget `t`
// because it's no longer relevant.
forget(t);
}
}
这篇关于`std::Mem::swap`是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文