指针的方法swap()
和std::ptr::swap()
有什么区别?
签名是相似的,它们的行为和我测试的一样。
pub unsafe fn swap(self, with: *mut T)
pub unsafe fn swap<T>(x: *mut T, y: *mut T)
至于std::mem::swap()
(用于引用而不是指针),在这种情况下,我们不能调用std::mem::swap()
,因为它需要两个可变的引用。例如,在这种情况下,我们将调用slice::swap()
。那std::ptr::swap()
呢
发布于 2022-11-22 13:48:13
ptr.swap()
和std::ptr::swap()
之间没有什么区别-- 前者的实施只是调用后者:
pub const unsafe fn swap(self, with: *mut T)
where
T: Sized,
{
// SAFETY: the caller must uphold the safety contract for `swap`.
unsafe { swap(self, with) }
}
根据医生们,mem::swap
和ptr::swap
之间唯一的区别是:
ptr::swap
对指针而不是引用进行操作。ptr::swap
允许指向值重叠。ptr::swap
不要求对指向数据进行初始化/满足指向类型的要求。除此之外,它们的语义是相同的。
https://stackoverflow.com/questions/74533592
复制相似问题