我目前正在尝试测试Rust中的一些RAII代码,并且我希望延迟删除一个值,直到特定的代码行。
在C#中,GC.KeepAlive防止对象在调用GC.KeepAlive之前被垃圾收集。从应用程序的角度来看,该方法本质上是一个no,但它保证了对对象的有效引用,直到代码流中的某个特定点。它主要用于测试。
是否有一种惯用的方法将一个值延迟到锈蚀的某个点?我正在尝试测试一些RAII代码,我更喜欢使用另一个Rust程序员可以识别的约定。
例如:
let foo = some_func();
// Force foo to be deallocated
// This line does something that, if foo were still alive, it would fail the test
some_other_func();发布于 2020-10-27 23:58:54
最简单的方法是显式地删除对象。当您调用mem::drop时,对象将被移动到该函数中,因此该对象必须存在于调用者之前,而不是在该点之后。这向其他Rust开发人员发出信号,表明您当时明确希望销毁。它不一定表明你为什么要破坏那里,所以你可能仍然需要一个评论,如果它不是显而易见的上下文。
例如,如果您有一个临时目录,并且需要保留它:
extern crate tempfile;
fn do_something() {
let tempdir = tempfile::TempDir::new();
// Do some things with your temporary directory.
std::mem::drop(tempdir);
// Do some things without your temporary directory.
}https://stackoverflow.com/questions/64563281
复制相似问题