What happens when I call std::mem::drop with a reference instead of an owned value?

心已入冬 提交于 2020-05-29 06:14:40

问题


fn main() {
    let k = "fire";

    drop(k);

    println!("{:?}", k);
}

Playground

Why am I still able to use k after dropping it? Does drop not deref a reference automatically? If yes, then why? What does the implementation of Drop look like for &str?


回答1:


What happens when I call std::mem::drop with a reference

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?

Because immutable pointers implement Copy. You pass in a copy of the reference and it's dropped.

Does drop not deref a reference automatically?

No, it does not.

what does the implementation of Drop look like for &str?

There isn't one for any kind of reference, immutable or mutable, so it's effectively 1:

impl Drop for &str {
    fn drop(&mut self) {}
}

See also:

  • Moved variable still borrowing after calling `drop`?
  • Why does a mutable reference to a dropped object still count as a mutable reference?

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.



来源:https://stackoverflow.com/questions/55314407/what-happens-when-i-call-stdmemdrop-with-a-reference-instead-of-an-owned-val

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!