gpt4 book ai didi

rust - 为什么我不能对一个永远不会超出范围的值进行静态引用?

转载 作者:行者123 更新时间:2023-12-03 11:27:28 26 4
gpt4 key购买 nike

为什么我不能对一个永远不会超出范围的值进行 'static 引用?

如果它永远不会超出范围,比如当函数调用永远不会在主线程中返回时,那么只要范围拥有数据,数据就会保持有效,这将适用于程序的生命周期。在那种情况下,我也应该能够在程序的整个生命周期内引用它,因为它在这段时间内保持有效,对吗?这是我的问题的示例:

fn noreturn() -> ! {
loop {}
}

fn main() {
// This value is never dropped or moved, and so it should last
// for 'static, right?
let not_dropped = 0usize;
// So I should be able to borrow it for 'static here, right?
let permanent_ref: &'static usize = &not_dropped;
// This never returns, and so the value is never dropped
// and the data stays valid,
noreturn()
// .. but the compiler complains that not_dropped is dropped
// here even though it's never dropped. Why?
}

如果保证永远不会到达具有此值的范围的末尾,那么我应该能够永远持有对该范围所拥有的有效值的引用,对吧?我在概念上是否遗漏了什么?

最佳答案

返回不等于不退出。例如,用 panic 替换您的循环(签名保持不变)。然后添加一个值,当它被删除时打印出来:

fn noreturn() -> ! {
panic!()
}

fn main() {
let not_dropped = Noisy;
noreturn()
}

struct Noisy;

impl Drop for Noisy {
fn drop(&mut self) {
eprintln!("I was dropped");
}
}

您会看到该值确实下降了。

另一种看待这个问题的方法是,如果您在子线程 1 中执行此操作,子线程 1 会生成子线程 2。线程 2 引用了 &'static 值,然后线程 1 退出并堆栈不见了。当线程 2 试图访问引用的值时,它是内存不安全的。

What if the noreturn function guaranteed no exit by just containing a loop, like in the example I showed? Is that a case where this should be possible?

Rust 中没有表面语法来保证函数永远运行,因此编译器无法为您保证这一点。但是,如果您知道编译器不知道的内容,则可以使用 unsafe 来表达。

例如,也许您知道您的函数调用了 process::abort(或者 panic 通过编译器选项实现为中止),因此任何代码都不可能可以在函数退出后运行。在那种情况下,我相信(但尚未验证)您可以使用 unsafe 将生命周期更改为 'static

也就是说,调用 Box::leak是获取 &'static 值的一种更简单的方法。

关于rust - 为什么我不能对一个永远不会超出范围的值进行静态引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66012399/

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