关于 std::mem::drop 函数?
跟着 Rust 权威指南学到了智能指针章节,关于 drop
函数有个疑问:
let x = 1;
drop(x);
println!("{}", x);
这段代码居然不报错?第二行我手动调用了 drop
函数,但 x
并没有失效,这是为什么呢?
回复
1个回答

test
2024-07-17
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.
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容