gpt4 book ai didi

rust - 在 Rust 中指向临时对象的原始指针可以吗?

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

我有这样一个函数:

extern {
fn foo(layout: *const RawLayout) -> libc::uint8_t;
}

fn bar(layout: Layout) -> bool {
unsafe {
foo(&layout.into() as *const _) != 0
}
}

其中 Layout 是可复制类型,可以将 .into() 转换为 RawLayout

我想确保我了解正在发生的事情,因为它是不安全的。据我了解,layout.into() 创建一个临时的 RawLayout,然后 & 引用它,并且 as * const _ 将其转换为原始指针 (*const RawLayout)。然后调用foo()函数并返回,最后丢弃临时的RawLayout

这样对吗?还是有一些棘手的理由让我不应该这样做?

最佳答案

你是对的。在这种情况下,首先调用 foo,然后删除 RawLayout。这在 The Rust Reference 中有解释。 (点击链接查看实际效果的具体示例):

The lifetime of temporary values is typically the innermost enclosing statement

但是,我宁愿听从 Shepmaster 的建议。显式引入局部变量将帮助代码的读者专注于更重要的事情,例如确保不安全代码是正确的(而不是必须弄清楚临时变量的确切语义)。

如何检查这个

您可以使用下面的代码来检查此行为:

struct Layout;
struct RawLayout;

impl Into<RawLayout> for Layout {
fn into(self) -> RawLayout {
RawLayout
}
}

impl Drop for RawLayout {
fn drop(&mut self) {
println!("Dropping RawLayout");
}
}

unsafe fn foo(layout: *const RawLayout) -> u8 {
println!("foo called");
1
}

fn bar(layout: Layout) -> bool {
unsafe {
foo(&layout.into() as *const _) != 0
}
}

fn main() {
bar(Layout);
}

输出是:

foo called
Dropping RawLayout

关于rust - 在 Rust 中指向临时对象的原始指针可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41815619/

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