ZhangHanDong / tao-of-rust-codes

《Rust编程之道》随书源码
https://ruststudy.github.io/tao_of_rust_docs/tao_of_rust/
MIT License
1.18k stars 170 forks source link

第 13 章 13.2.4 节 Drop 检查: 在析构函数中手动指定析构顺序的源码代码过期 #311

Open Kreedzt opened 3 years ago

Kreedzt commented 3 years ago

ManuallyDrop 源码代码过期

书中的 ManuallyDrop 源码及描述

pub union ManuallyDrop<T> { value: T }
impl<T> ManuallyDrop<T> {
  pub const fn new(Value: T) -> ManuallyDrop<T> {
    ManuallyDrop { value: value }
  }
  pub unsafe fn drop(slot: &mut ManuallyDrop<T>) {
    ptr::drop_in_place(&mut slot.value)
  }
}

ManuallyDrop 是一个联合体, Rust 不会为联合体自动实现 Drop. 因为联合体是所有的字段共用内存, 不能随便被析构, 否则会引起未定义行为.

Rust 1.48.0 版本下的源码

#[stable(feature = "manually_drop", since = "1.20.0")]
#[lang = "manually_drop"]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct ManuallyDrop<T: ?Sized> {
    value: T,
}

impl<T> ManuallyDrop<T> {
    #[must_use = "if you don't need the wrapper, you can use `mem::forget` instead"]
    #[stable(feature = "manually_drop", since = "1.20.0")]
    #[rustc_const_stable(feature = "const_manually_drop", since = "1.36.0")]
    #[inline(always)]
    pub const fn new(value: T) -> ManuallyDrop<T> {
        ManuallyDrop { value }
    }
}

impl<T: ?Sized> ManuallyDrop<T> {
    #[stable(feature = "manually_drop", since = "1.20.0")]
    #[inline]
    pub unsafe fn drop(slot: &mut ManuallyDrop<T>) {
        // SAFETY: we are dropping the value pointed to by a mutable reference
        // which is guaranteed to be valid for writes.
        // It is up to the caller to make sure that `slot` isn't dropped again.
        unsafe { ptr::drop_in_place(&mut slot.value) }
    }
}

已不再是联合体定义

Kreedzt commented 3 years ago

与此重复 -> #110