[英]What happens when I call std::mem::drop with a reference instead of an owned value?
fn main() {
let k = "fire";
drop(k);
println!("{:?}", k);
}
Why am I still able to use k
after dropping it?为什么我删除后仍然可以使用k
? Does drop
not deref a reference automatically? drop
不会自动取消引用吗? If yes, then why?如果是,那为什么? What does the implementation of Drop
look like for &str
? &str
的Drop
实现是什么样的?
What happens when I call
std::mem::drop
with a reference当我使用引用调用std::mem::drop
时会发生什么
The reference itself is dropped.引用本身被删除。
a reference instead of an owned value引用而不是拥有的值
A reference is a value.引用是一个值。
Why am I still able to use
k
after dropping it?为什么我删除后仍然可以使用k
?
Because immutable pointers implement Copy
.因为不可变指针实现了Copy
。 You pass in a copy of the reference and it's dropped.您传入引用的副本,然后将其删除。
Does
drop
not deref a reference automatically?drop
不会自动取消引用吗?
No, it does not.不,不是的。
what does the implementation of
Drop
look like for&str
?&str
的Drop
实现是什么样的?
There isn't one for any kind of reference, immutable or mutable, so it's effectively 1 :没有任何类型的参考,不可变或可变的,所以它实际上是1 :
impl Drop for &str {
fn drop(&mut self) {}
}
See also:也可以看看:
1 — As Peter Hall points out , there is a difference between having an empty Drop
implementation and having no user-provided Drop
implementation, but for the purposes of this question they are the same. 1 — 正如Peter Hall 所指出的,拥有空Drop
实现和没有用户提供的Drop
实现之间存在差异,但就本问题而言,它们是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.