This article似乎暗示着 Rust 文档中使用术语“移动”并不意味着副本,而是在编译时转移所有权的可能性。具体参见这段引用:
The compiler enforces that there is only a single owner. Assigning the pointer to a new location transfers ownership (known as a move for short). Consider this program:
这是正确的吗?所有权转移/移动实际上并不是在运行时复制,而只是编译时抽象。
最佳答案
不,移动仍然是副本(在memcpy
的意义上),尽管不一定是整个数据结构。但是,它具有您列出的编译时语义。也就是说,
let a = ~[1,2,3];
let b = a; // copies one word (the pointer), "moves" the data.
let c = b.clone(); // copies the data too.
(请注意,我使用了 b.clone()
而不是 copy b
,因为 Copy is being removed ,并替换为 Clone
,更强大/更灵活。)
这种复制行为是需要发生的,因为 Rust 中的(许多)变量是明确的内存块(就像 C/C++ 中的变量一样),并且如果某些东西具有特定值,则该值必须位于适当的位置内存;这意味着移动(通常涉及将数据从一个变量传输到另一个变量)必须实际执行复制。
关于rust - 自有指针移动的语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602715/