关于 std::mem::drop 函数?

跟着 Rust 权威指南学到了智能指针章节,关于 drop 函数有个疑问:

let x = 1;
drop(x);
println!("{}", x);

这段代码居然不报错?第二行我手动调用了 drop 函数,但 x 并没有失效,这是为什么呢?

阅读 2.3k
2 个回答

x 是一个“简单”类型,实现了 Copy Trait 。所以 x 是 copy 进去的,不会失效。

drop 是依靠所有权转移拿到参数的所有权,然后释放内存的。实现了 Copy Trait 的类型(“简单”类型)不会发生所有权转移,而是会直接拷贝。所以 drop 不掉。

https://doc.rust-lang.org/boo...

Rust has a special annotation called the Copy trait that we can place on types that are stored on the stack, as integers are (we’ll talk more about traits in Chapter 10). If a type implements the Copy trait, variables that use it do not move, but rather are trivially copied, making them still valid after assignment to another variable.
pub fn drop<T>(_x: T) 
Disposes of a value.

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.

https://doc.rust-lang.org/std...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进