简体   繁体   English

将* mut T强制解除引用到* mut ManuallyDrop <T>是不确定的行为?

[英]Is it undefined behavior to dereference a *mut T cast to *mut ManuallyDrop<T>?

According to the docs, ManuallyDrop<T> is a zero-cost wrapper. 根据文档, ManuallyDrop<T>是一个零成本的包装器。 Does that mean I can dereference a raw pointer to ManuallyDrop<T> casted from a raw pointer to T ? 这是否意味着我可以取消引用从原始指针到T ManuallyDrop<T>的原始指针?

ManuallyDrop is declared as #[repr(transparent)] : ManuallyDrop声明为#[repr(transparent)]

#[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,
}

#[repr(transparent)] is described as : #[repr(transparent)] 描述为

The attribute can be applied to a newtype-like structs that contains a single field. 该属性可以应用于包含单个字段的类型类型的结构。 It indicates that the newtype should be represented exactly like that field's type, ie, the newtype should be ignored for ABI purpopses [sic]: not only is it laid out the same in memory, it is also passed identically in function calls. 它表示newtype应该与该字段的类型完全相同,即,对于ABI purpopses [sic]应该忽略newtype:它不仅在内存中布局相同,而且在函数调用中也相同地传递。

[...] [...]

PtrWithCustomZst is also represented exactly like *const Foo PtrWithCustomZst也表示与*const Foo完全相同

I believe that it is safe to perform this transformation. 我相信这种转变是安全的。


The real question is why would you want to do this? 真正的问题是你为什么要这样做? Having a pointer to a ManuallyDrop structure seems rather pointless. 指向ManuallyDrop结构的指针似乎毫无意义。 If you have a pointer to a T , the underlying value won't be dropped to start with. 如果您有一个指向T的指针,则不会删除基础值。 If you convert the pointer to a reference (while ensuring you uphold the rules of references), the reference won't drop the underlying value either. 如果将指针转换为引用(同时确保遵守引用规则),则引用也不会丢弃基础值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM