为什么 std::rc::Rc<>不复制? [英] Why is std::rc::Rc<> not Copy?

查看:52
本文介绍了为什么 std::rc::Rc<>不复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么 Rc<> 不是 Copy 吗?

Can someone explain to me why Rc<> is not Copy?

我正在编写使用大量共享指针的代码,并且必须一直键入 .clone() 使我很紧张.

I'm writing code that uses a lot of shared pointers, and having to type .clone() all the time is getting on my nerves.

在我看来 Rc<> 应该只包含一个指针,它是一个固定大小,所以类型本身应该是 Sized,因此 复制,对吗?

It seems to me that Rc<> should just consist of a pointer, which is a fixed size, so the type itself should be Sized and hence Copy, right?

我错过了什么吗?

推荐答案

在我看来 Rc<> 应该只包含一个指针,它是一个固定大小,所以类型本身应该是 Sized,因此 复制,对吗?

It seems to me that Rc<> should just consist of a pointer, which is a fixed size, so the type itself should be Sized and hence Copy, right?

这并不完全正确.RcR 引用 C 的缩写.这意味着该类型会跟踪有多少引用指向拥有的数据.这样我们就可以同时拥有多个所有者并安全地释放数据,一旦引用计数达到 0.

This is not quite true. Rc is short for Reference Counted. This means that the type keeps track of how many references point to the owned data. That way we can have multiple owners at the same time and safely free the data, once the reference count reaches 0.

但是我们如何使引用计数器保持有效和最新?确切地说,每当创建新的引用/所有者以及删除引用/所有者时,我们都必须做一些事情.具体来说,我们必须在前一种情况下增加计数器,在后一种情况下减少它.

But how do we keep the reference counter valid and up to date? Exactly, we have to do something whenever a new reference/owner is created and whenever a reference/owner is deleted. Specifically, we have to increase the counter in the former case and decrease it in the latter.

通过实施 Drop 减少计数器,Rust 等价于析构函数.这个 drop() 函数在变量超出范围时执行 - 非常适合我们的目标.

The counter is decreased by implementing Drop, the Rust equivalent of a destructor. This drop() function is executed whenever a variable goes out of scope – perfect for our goal.

但是我们什么时候做增量呢?你猜对了:在 clone() 中.Copy trait,根据定义, 表示可以通过复制位来复制类型:

But when do we do the increment? You guessed it: in clone(). The Copy trait, by definition, says that a type can be duplicated just by copying bits:

可以通过简单复制位来复制的类型(即 memcpy).

Types that can be copied by simply copying bits (i.e. memcpy).

在我们的例子中这不是真的,因为:是的,我们只是复制位",但我们也做了额外的工作!我们确实需要增加我们的引用计数器!

This is not true in our case, because: yes, we "just copy bits", but we also do additional work! We do need to increment our reference counter!

这篇关于为什么 std::rc::Rc&lt;&gt;不复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆