跟着 Rust 权威指南学到了智能指针章节,关于 drop
函数有个疑问:
let x = 1;
drop(x);
println!("{}", x);
这段代码居然不报错?第二行我手动调用了 drop
函数,但 x
并没有失效,这是为什么呢?
跟着 Rust 权威指南学到了智能指针章节,关于 drop
函数有个疑问:
let x = 1;
drop(x);
println!("{}", x);
这段代码居然不报错?第二行我手动调用了 drop
函数,但 x
并没有失效,这是为什么呢?
pub fn drop<T>(_x: T)
This does so by calling the argument’s implementation of Drop.
This effectively does nothing for types which implement Copy, e.g. integers. Such values are copied and then moved into the function, so the value persists after this function call.
This function is not magic; it is literally defined as
pub fn drop<T>(_x: T) { }
Because _x is moved into the function, it is automatically dropped before the function returns.
7 回答5.3k 阅读
1 回答3.3k 阅读
2 回答840 阅读
1 回答884 阅读
x 是一个“简单”类型,实现了 Copy Trait 。所以 x 是 copy 进去的,不会失效。
drop 是依靠所有权转移拿到参数的所有权,然后释放内存的。实现了 Copy Trait 的类型(“简单”类型)不会发生所有权转移,而是会直接拷贝。所以 drop 不掉。
https://doc.rust-lang.org/boo...