在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
andv2
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.
我的问题是,当
v1
和v2
超出范围时,为什么需要两次释放数据缓冲区?除了“销毁” v1
和v2
之外,我们是否只能释放一次数据缓冲区?我知道v1
和v2
实际上是值,而不是引用,但是不使它们具有上述行为的“智能引用”的原理是什么?
最佳答案
[...] what is the rationale for not making them "smart references"?
性能,主要是。 Rust完全是关于“零成本抽象”(由C++创造的一个术语)。如果程序员不需要该语言,则不会导致运行时开销。这样的“智能引用”将是引用计数的指针(例如Rust中的
Rc
或Arc
或C++中的shared_ptr
)或需要垃圾回收器。这两个解决方案都确实有此开销。
关于rust - 为什么Rust中的默认行为是执行赋值移动,而不是仅仅为该值创建另一个 “reference”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59420238/