有没有办法在 Rust 中删除静态生命周期对象? [英] Is there a way to drop a static lifetime object in Rust?

查看:32
本文介绍了有没有办法在 Rust 中删除静态生命周期对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在寻找答案时,我发现 这个问题,但是没有提到静态生命周期对象.这个答案中提到的方法(在对象上调用 drop() )可以用于静态生命周期对象吗?

When searching for an answer, I found this question, however there is no mention of static lifetime objects. Can the method mentioned in this answer (calling drop() on the object) be used for static lifetime objects?

我在想象一个类似链表的情况.您需要在程序的整个生命周期内(可能)保留列表的节点,但是您也可以从列表中删除项目.在程序的整个执行过程中将它们留在内存中似乎很浪费.

I was imagining a situation like a linked list. You need to keep nodes of the list around for (potentially) the entire lifetime of the program, however you also may remove items from the list. It seems wasteful to leave them in memory for the entire execution of the program.

谢谢!

推荐答案

没有.static 的关键在于它是静态的:它在内存中有一个固定地址,不能从那里移动.因此,每个人都可以自由地引用该对象,因为只要程序正在执行,它就可以保证存在.这就是为什么您只能以 &'static 引用的形式使用 static 并且永远不能声明所有权.

No. The very point of a static is that it's static: It has a fixed address in memory and can't be moved from there. As a consequence, everybody is free to have a reference to that object, because it's guaranteed to be there as long as the program is executing. That's why you only get to use a static in the form of a &'static-reference and can never claim ownership.

此外,为了节省内存而这样做是没有意义的:对象被烘焙到可执行文件中并在访问时映射到内存.可能发生的只是操作系统放弃内存映射.然而,由于从来没有从堆中分配内存,因此没有任何节省.

Besides, doing this for the purpose of memory conservation is pointless: The object is baked into the executable and mapped to memory on access. All that could happen is for the OS to relinquish the memory mapping. Yet, since the memory is never allocated from the heap in the first place, there is no saving to be had.

可以做的唯一一件事就是使用不安全的可变访问替换对象.这既危险(因为编译器可以自由地假设对象实际上没有改变)又毫无意义,因为内存无法释放,因为它是可执行文件内存映射的一部分.

The only thing you could do is to replace the object using unsafe mutable access. This is both dangerous (because the compiler is free to assume that the object does not in fact change) and pointless, due to the fact that the memory can't be freed, as it's part of the executable's memory mapping.

这篇关于有没有办法在 Rust 中删除静态生命周期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆