何时使用 Rc 与 Box? [英] When to use Rc vs Box?

查看:74
本文介绍了何时使用 Rc 与 Box?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,它同时使用了 RcBox;那些有什么区别?哪个更好?

I have the following code which uses both Rc and Box; what is the difference between those? Which one is better?

use std::rc::Rc;

fn main() {
    let a = Box::new(1);
    let a1 = &a;
    let a2 = &a;
    let b = Rc::new(1);
    let b1 = b.clone();
    let b2 = b.clone();

    println!("{} {}", a1, a2);
    println!("{} {}", b1, b2);
}

游乐场链接

推荐答案

Rc 提供共享所有权,因此默认情况下其内容不能改变,而 Box 提供独占所有权,因此允许更改:

Rc provides shared ownership so by default its contents can't be mutated, while Box provides exclusive ownership and thus mutation is allowed:

use std::rc::Rc;

fn main() {
    let mut a = Box::new(1);
    let mut b = Rc::new(1);

    *a = 2; // works
    *b = 2; // doesn't
}

另外Rc不能在线程间发送,因为它没有实现Send.

In addition Rc cannot be sent between threads, because it doesn't implement Send.

底线是它们用于不同的事情:如果您不需要共享访问,请使用 Box;否则,使用 Rc(或 Arc 用于多线程共享使用)并记住您将需要 CellRefCell 用于内部可变性.

The bottom line is they are meant for different things: if you don't need shared access, use Box; otherwise, use Rc (or Arc for multi-threaded shared usage) and keep in mind you will be needing Cell or RefCell for internal mutability.

这篇关于何时使用 Rc 与 Box?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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