gpt4 book ai didi

rust - 取消引用 *mut T 转换为 *mut ManuallyDrop 是未定义的行为吗?

转载 作者:行者123 更新时间:2023-11-29 07:58:00 33 4
gpt4 key购买 nike

根据文档,ManuallyDrop<T>是一个零成本包装器。这是否意味着我可以取消引用指向 ManuallyDrop<T> 的原始指针从原始指针转换为 T

最佳答案

ManuallyDropdeclared 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 的指针,则不会删除基础值。如果将指针转换为引用(同时确保遵守引用规则),引用也不会删除基础值。

关于rust - 取消引用 *mut T 转换为 *mut ManuallyDrop<T> 是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53018458/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com