取消引用 *mut T 转换为 *mut ManuallyDrop<T> 是未定义的行为吗?
Is it undefined behavior to dereference a *mut T cast to *mut ManuallyDrop<T>?
根据文档,ManuallyDrop<T>
是一个零成本包装器。这是否意味着我可以取消引用从指向 T
的原始指针转换为 ManuallyDrop<T>
的原始指针?
ManuallyDrop
是 declared as #[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)]
是 described as:
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, i.e., 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.
[...]
PtrWithCustomZst
is also represented exactly like *const Foo
我相信执行此转换是安全的。
真正的问题是为什么你想这样做?拥有指向 ManuallyDrop
结构的指针似乎毫无意义。如果您有一个指向 T
的指针,则不会删除基础值。如果将指针转换为引用(同时确保遵守引用规则),引用也不会删除基础值。
根据文档,ManuallyDrop<T>
是一个零成本包装器。这是否意味着我可以取消引用从指向 T
的原始指针转换为 ManuallyDrop<T>
的原始指针?
ManuallyDrop
是 declared as #[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)]
是 described as:
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, i.e., 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.
[...]
PtrWithCustomZst
is also represented exactly like*const Foo
我相信执行此转换是安全的。
真正的问题是为什么你想这样做?拥有指向 ManuallyDrop
结构的指针似乎毫无意义。如果您有一个指向 T
的指针,则不会删除基础值。如果将指针转换为引用(同时确保遵守引用规则),引用也不会删除基础值。