use*_*965 5 release ownership rust
根据Rust编程语言:
在Rust中,您可以指定在值超出范围时运行特定的代码位,编译器将自动插入此代码
程序员不应该显式地释放资源(drop
从Drop
特征中调用函数),drop
每当所有者超出范围时Rust都会调用,这在编译期间完成,但是drop
如果它依赖于Rust,Rust怎么可能知道何时调用关于运行时信息?
extern crate rand;
use rand::Rng;
struct Foo {}
impl Drop for Foo {
fn drop(&mut self) {
println!("drop occurs");
}
}
fn main() {
let foo = Foo {};
if rand::thread_rng().gen() {
let _t = foo; // move foo to _t
} // 1) drop occurs here if random bool is true
} // 2) drop occurs here if random bool is false
Run Code Online (Sandbox Code Playgroud)
在此代码中,当编译器插入代码以释放资源时,将调用drop
放置在何处,放置1)
或2)
?由于在编译期间无法知道,我认为调用应放在两个地方,但只能调用一个以避免悬空指针.
Rust如何处理这种情况以保证内存安全?
归档时间: |
|
查看次数: |
138 次 |
最近记录: |