rust - 为什么Rust中的默认行为是执行赋值移动,而不是仅仅为该值创建另一个 “reference”?

标签 rust

在Rust中,如果您执行以下操作:

let v1 = String::from("hello");
let v2 = v1;
println!("{}", v1);

您将收到编译器错误,因为Rust中的=执行了移动,而不是复制或“共享”。

我正在阅读this article,其中对此进行了更详细的讨论:

But there is a bigger problem, regarding deallocation. If share semantics was used, both v1 and v2 would own the single data buffer, and so when they are deallocated, the same heap buffer would be deallocated twice. A buffer cannot be allocated twice, without causing memory corruption and consequently program malfunction. To solve this problem, the languages that use share semantics do not deallocate memory at the end of the scope of the variable using such memory, but resort to garbage collection.



我的问题是,当v1v2超出范围时,为什么需要两次释放数据缓冲区?除了“销毁” v1v2之外,我们是否只能释放一次数据缓冲区?我知道v1v2实际上是值,而不是引用,但是不使它们具有上述行为的“智能引用”的原理是什么?

最佳答案

[...] what is the rationale for not making them "smart references"?



性能,主要是。 Rust完全是关于“零成本抽象”(由C++创造的一个术语)。如果程序员不需要该语言,则不会导致运行时开销。这样的“智能引用”将是引用计数的指针(例如Rust中的RcArc或C++中的shared_ptr)或需要垃圾回收器。这两个解决方案都确实有此开销。

关于rust - 为什么Rust中的默认行为是执行赋值移动,而不是仅仅为该值创建另一个 “reference”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59420238/

相关文章:

rust - 如何将 rustfmt 配置为不为匹配的不安全 block 模式发出对齐空格?

unit-testing - 如何卡住考试时间?

reference - `mut a: &T` 和 `a: &mut T` 有什么区别?

Rust 生命周期错误

multithreading - 为什么这些线程在完成工作之前退出?

rust - 解决通过引用获取参数的闭包的类型不匹配

Rust actix-web 线程不安全移动

rust - 由于实验功能无法安装沙沙声

reference - 引用的身份关闭

generics - 泛型类型的泛型构造函数的显式类型注释