为什么Rust编译器允许在将值A.b
移动到a
之后突变字段drop
?
struct A {
b: usize
}
fn main() {
let mut a = A { b: 0 };
drop(a);
a.b = 1; // <---- Why is this allowed?
}
编译器不应该在该行上出错吗?
(如果在调用drop()
后尝试使用该值,编译器确实会出错)
进一步调查:
我想也许这只是因为编译器知道写入“死”但它似乎正在生成实际执行写操作的代码。 MIR
的{{1}}包含以下内容:
main()
(请注意bb0: {
StorageLive(_1); // scope 0 at <anon>:6:9: 6:14
_1 = A { b: const 0usize }; // scope 0 at <anon>:6:17: 6:27
StorageLive(_3); // scope 1 at <anon>:8:10: 8:11
_3 = _1; // scope 1 at <anon>:8:10: 8:11
_2 = std::mem::drop::<A>(_3) -> bb1; // scope 1 at <anon>:8:5: 8:12
}
bb1: {
StorageDead(_3); // scope 1 at <anon>:8:13: 8:13
(_1.0: usize) = const 1usize; // scope 1 at <anon>:10:5: 10:12
_0 = (); // scope 1 at <anon>:5:11: 11:2
StorageDead(_1); // scope 0 at <anon>:11:2: 11:2
return; // scope 0 at <anon>:11:2: 11:2
}
中的(_1.0: usize) = const 1usize;
行)
并且Debug构建包含此程序集:
bb1