Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Kreedzt opened this issue Dec 1, 2020 · 1 comment
Labels
代码过期 代码因为Rust版本更新而过期 第十三章 第十三章

Comments

@Kreedzt
Copy link

Kreedzt commented Dec 1, 2020

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) }
    }
}

已不再是联合体定义

@ZhangHanDong ZhangHanDong added 第十三章 第十三章 代码过期 代码因为Rust版本更新而过期 labels Dec 2, 2020
@Kreedzt
Copy link
Author

Kreedzt commented Dec 9, 2020

与此重复 -> #110

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
代码过期 代码因为Rust版本更新而过期 第十三章 第十三章
Projects
None yet
Development

No branches or pull requests

2 participants