« Rc<T> cannot be sent between threads safely » : Rc et Arc en Rust, le modèle mental (E0277) "Rc<T> cannot be sent between threads safely": Rc and Arc in Rust, the mental model (E0277)

Un Rc<T> est une boîte à plusieurs propriétaires : Rc::clone incrémente un compteur sans copier la valeur, et elle est libérée quand il retombe à zéro. Pourquoi Rc refuse de changer de thread (E0277) et ce qu'Arc change, pourquoi le contenu est en lecture seule (E0596), et le cycle qui fuit, avec Weak comme issue. Animation et sorties réelles de rustc.An Rc<T> is a box with several owners: Rc::clone increments a counter without copying the value, and it is freed when the counter falls back to zero. Why Rc refuses to change threads (E0277) and what Arc changes, why the content is read-only (E0596), and the cycle that leaks, with Weak as the way out. Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
PointeursPointers
PubliéPublished

En bref. Box donne un seul propriétaire à une valeur sur le tas. Parfois il en faut plusieurs : une configuration lue par deux services, un nœud référencé par deux autres. Rc<T> le permet avec un compteur. Et le jour où l’un des propriétaires part dans un autre thread, rustc répond E0277, Rc<String> cannot be sent between threads safely. La réponse tient en une lettre de plus : Arc.

Le modèle en une phrase

Un Rc<T> est une boîte à plusieurs propriétaires : chaque clone ajoute un propriétaire et incrémente un compteur, chaque disparition le décrémente, et la valeur est libérée quand le compteur retombe à zéro.

Trois conséquences suivent. Le partage impose la lecture seule. Le compteur de Rc n’est pas fait pour plusieurs threads, celui d’Arc l’est. Et un compteur qui ne retombe jamais à zéro est une fuite : c’est le cycle, second onglet de l’animation.

In short. Box gives a heap value a single owner. Sometimes you need several: a configuration read by two services, a node referenced by two others. Rc<T> allows it with a counter. And the day one of the owners leaves for another thread, rustc answers E0277, Rc<String> cannot be sent between threads safely. The answer is one letter longer: Arc.

The model in one sentence

An Rc<T> is a box with several owners: each clone adds an owner and increments a counter, each disappearance decrements it, and the value is freed when the counter falls back to zero.

Three consequences follow. Sharing imposes read-only access. Rc’s counter isn’t made for several threads, Arc’s is. And a counter that never falls back to zero is a leak: that’s the cycle, the animation’s second tab.

let config = Rc::new(Config { nom: "prod".into() });
Rc::strong_count(&config) // 1
Rc<Config>Rc<Config>une valeur, plusieurs propriétairesone value, several ownersconfig8 o8 Bapi.configlâchédroppedworker.configsortiout of scopeConfig0x…4d01compteur fortstrong countcompteur fort au fil du codestrong count over the code01231newnewdrop(api)la valeur vit tant qu’il reste au moins un propriétairethe value lives as long as at least one owner remainsun propriétaire · compteur fort : 1one owner · strong count: 1
  1. Rc::new range la valeur sur le tas, comme Box, avec un compteur à côté d'elle. Un propriétaire, compteur à 1.Rc::new stores the value on the heap, like Box, with a counter next to it. One owner, counter at 1.
  2. Rc::clone ne copie pas la Config : il copie le pointeur et incrémente le compteur. Trois propriétaires, une seule valeur, à la même adresse (Rc::ptr_eq rend true).Rc::clone doesn't copy the Config: it copies the pointer and increments the counter. Three owners, a single value, at the same address (Rc::ptr_eq returns true).
  3. Chaque propriétaire qui disparaît décrémente le compteur. worker sort de sa portée, config est lâché : le compteur retombe à 1, et la valeur reste lisible par api. Aucun propriétaire n'est le « vrai ».Each owner that goes away decrements the counter. worker leaves its scope, config is dropped: the counter falls back to 1, and the value stays readable through api. No owner is the "real" one.
  4. Le dernier propriétaire disparaît, le compteur atteint 0, et Drop libère la valeur : « Config libérée » s'affiche avant « fin de main ». Le moment dépend de l'exécution, plus de la seule lecture du code.The last owner goes away, the counter reaches 0, and Drop frees the value: "Config libérée" prints before "fin de main". The moment depends on execution, no longer on reading the code alone.
Le comptage de références avec Rc<T> en Rust : Rc::clone ajoute un propriétaire et incrémente le compteur sans copier la valeur ; chaque propriétaire qui disparaît le décrémente, et la valeur est libérée à zéro.Reference counting with Rc<T> in Rust: Rc::clone adds an owner and increments the counter without copying the value; each owner that goes away decrements it, and the value is freed at zero.

Quand un seul propriétaire ne suffit plus

struct Service { config: Box<Config> }

let config = Box::new(Config { nom: "prod".to_string() });
let api = Service { config };
let worker = Service { config };
error[E0382]: use of moved value: `config`
 --> partage_box.rs:8:28
  |
6 |     let config = Box::new(Config { nom: "prod".to_string() });
  |         ------ move occurs because `config` has type `Box<Config>`, which does not implement the `Copy` trait
7 |     let api = Service { config };
  |                         ------ value moved here
8 |     let worker = Service { config };
  |                            ^^^^^^ value used here after move

Une boîte a un propriétaire, et api l’a prise. On pourrait cloner la Config, mais on aurait deux configurations qui divergent à la première modification. On pourrait prêter &Config, mais il faudrait alors prouver qui vit le plus longtemps, avec des lifetimes dans chaque Service. Quand aucun propriétaire n’est clairement « le dernier », il reste à les compter.

Rc::clone ajoute un propriétaire

let config = Rc::new(Config { nom: "prod".to_string() });
let api = Service { config: Rc::clone(&config) };
{
    let worker = Service { config: Rc::clone(&config) };
    println!("même valeur    : {}", Rc::ptr_eq(&api.config, &worker.config));
}
drop(config);
println!("lecture        : {}", api.config.nom);
drop(api);
println!("fin de main");
après new      : 1
après api      : 2
après worker   : 3
même valeur    : true
adresses       : 0x102f6d4d0 0x102f6d4d0
worker sorti   : 2
config lâché   : 1
lecture        : prod
Config libérée (prod)
fin de main

Rc::clone ne touche pas à la Config. Il copie un pointeur de 8 octets et ajoute 1 au compteur rangé à côté de la valeur :

 la pile                          le tas
┌────────────────┐
│ config       ●─┼──────┐      ┌──────────────────────┐
├────────────────┤      ├─────▶│ compteur fort : 3    │
│ api.config   ●─┼──────┤      ├──────────────────────┤
├────────────────┤      │      │ Config { nom: prod } │
│ worker.config●─┼──────┘      └──────────────────────┘
└────────────────┘                    0x…4d0
   8 o chacun

La suite est la lecture de la sortie. worker sort de sa portée : 2. drop(config) lâche la variable d’origine : 1, et la valeur reste lisible par api, car aucun propriétaire n’est le « vrai ». drop(api) : 0, et Drop libère la valeur, avant « fin de main ».

Avec Box, le moment de la libération se lisait dans le code. Avec Rc, il dépend de l’ordre dans lequel les propriétaires disparaissent à l’exécution. C’est le prix du partage.

Partagé, donc en lecture seule : E0596

let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
a.push(4);
error[E0596]: cannot borrow data in an `Rc` as mutable
 --> mutable.rs:6:5
  |
6 |     a.push(4);
  |     ^ cannot borrow as mutable
  |
  = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Vec<i32>>`

C’est la règle de l’emprunt qui revient : plusieurs lecteurs, ou un seul écrivain. Un Rc a par construction plusieurs lecteurs, il ne donne donc que des &T. Rc::make_mut respecte la règle en clonant la valeur si elle est partagée :

let mut a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
Rc::make_mut(&mut a).push(4);
[1, 2, 3, 4] [1, 2, 3]
même valeur : false

a a reçu sa propre copie, b garde l’ancienne : c’est de la copie à l’écriture. Pour que les deux voient la modification, il faut la mutabilité intérieure, Rc<RefCell<T>>, sujet du prochain numéro.

Entre threads : E0277, et Arc

let config = Rc::new(String::from("prod"));
let copie = Rc::clone(&config);
let h = thread::spawn(move || {
    println!("{copie}");
});
error[E0277]: `Rc<String>` cannot be sent between threads safely
   --> thread_rc.rs:7:27
    |
  7 |       let h = thread::spawn(move || {
    |               ------------- ^------
    |               |             |
    |  _____________|_____________within this `{closure@thread_rc.rs:7:27: 7:34}`
    | |             |
    | |             required by a bound introduced by this call
  8 | |         println!("{copie}");
  9 | |     });
    | |_____^ `Rc<String>` cannot be sent between threads safely
    |
    = help: within `{closure@thread_rc.rs:7:27: 7:34}`, the trait `Send` is not implemented for `Rc<String>`

Le compteur d’un Rc est un entier ordinaire. Si deux threads font +1 au même instant, l’un des deux peut être perdu : le compteur atteint zéro trop tôt, et la valeur est libérée alors qu’un propriétaire la lit encore. Rust ne laisse pas ce programme exister : thread::spawn exige que ce qu’on lui donne soit Send, et Rc ne l’est pas. C’est une borne de trait comme une autre, vérifiée à la compilation.

let config = Arc::new(String::from("prod"));
let copie = Arc::clone(&config);
let h = thread::spawn(move || {
    println!("dans le thread : {copie}, compteur {}", Arc::strong_count(&copie));
});
h.join().unwrap();
println!("après join     : compteur {}", Arc::strong_count(&config));
dans le thread : prod, compteur 2
après join     : compteur 1

Arc est le même modèle avec un compteur atomique : chaque +1 et chaque -1 est une opération indivisible, sûre depuis plusieurs threads. Même interface, même taille (8 octets). Le thread termine, sa copie disparaît, le compteur retombe à 1.

Le cycle : la fuite que Rust n’empêche pas

struct Noeud {
    nom: &'static str,
    autre: RefCell<Option<Rc<Noeud>>>,
}

let a = Rc::new(Noeud { nom: "a", autre: RefCell::new(None) });
let b = Rc::new(Noeud { nom: "b", autre: RefCell::new(Some(Rc::clone(&a))) });
*a.autre.borrow_mut() = Some(Rc::clone(&b));
println!("a : {} / b : {}", Rc::strong_count(&a), Rc::strong_count(&b));
println!("fin de main");
a : 2 / b : 2
fin de main

Noeud implémente Drop et affiche « libéré ». Rien ne s’affiche. À la fin de main, les variables a et b disparaissent et chaque compteur passe de 2 à 1 : a est encore possédé par b, b par a.

        ┌──────── Rc ────────┐
        │                    ▼
   ┌─────────┐          ┌─────────┐
   │ Noeud a │          │ Noeud b │      compteurs : 1 et 1
   │ fort: 1 │          │ fort: 1 │      jamais 0, jamais libérés
   └─────────┘          └─────────┘
        ▲                    │
        └──────── Rc ────────┘

Le programme compile sans avertissement et ne viole aucune garantie : Rust promet qu’on ne lira jamais une mémoire invalide, pas qu’on rendra toute la mémoire. Un comptage de références ne voit pas les cycles.

Weak : connaître sans posséder

struct Noeud {
    nom: &'static str,
    enfant: RefCell<Option<Rc<Noeud>>>,
    parent: RefCell<Weak<Noeud>>,
}

*parent.enfant.borrow_mut() = Some(Rc::clone(&enfant));
*enfant.parent.borrow_mut() = Rc::downgrade(&parent);
parent : fort 1 faible 1
enfant : fort 2 faible 0
upgrade : parent
parent libéré
upgrade : personne
fin de main
enfant libéré

Un Weak est un lien qui ne compte pas dans le compteur fort. Le parent possède l’enfant, l’enfant ne fait que connaître son parent. Le compteur fort du parent reste à 1 : drop(parent) le libère. Comme la valeur peut avoir disparu, un Weak ne se lit pas directement : upgrade() rend une Option, Some tant que le parent vit, None ensuite. L’absence est dans le type.

La question à se poser devant un graphe : qui possède qui ? Les liens de possession vont dans un sens (Rc), les liens de retour sont des Weak.

Ce que l’image cache

  • Rc::clone(&x) plutôt que x.clone(). Les deux font la même chose (compteur à 2, ptr_eq vrai). La forme longue signale au lecteur un clone bon marché, pas une copie profonde.
  • Arc ne rend pas le contenu modifiable. Il ne protège que le compteur. Pour écrire depuis plusieurs threads, il faut un verrou : Arc<Mutex<T>>.
  • Arc partout n’est pas gratuit. Les opérations atomiques coûtent plus cher qu’un +1. Dans un seul thread, Rc suffit, et le compilateur te préviendra le jour où ce ne sera plus vrai.
  • Rc n’est pas le premier réflexe. Un propriétaire et des emprunts &T suffisent le plus souvent, sans compteur ni allocation. Rc sert quand aucun propriétaire ne survit clairement aux autres.
  • Le compteur vit sur le tas, avec la valeur. Rc<T>, Arc<T> et Weak<T> font 8 octets sur la pile ; les compteurs fort et faible sont rangés à côté de la valeur.

Pour aller plus loin

When a single owner is no longer enough

struct Service { config: Box<Config> }

let config = Box::new(Config { nom: "prod".to_string() });
let api = Service { config };
let worker = Service { config };
error[E0382]: use of moved value: `config`
 --> partage_box.rs:8:28
  |
6 |     let config = Box::new(Config { nom: "prod".to_string() });
  |         ------ move occurs because `config` has type `Box<Config>`, which does not implement the `Copy` trait
7 |     let api = Service { config };
  |                         ------ value moved here
8 |     let worker = Service { config };
  |                            ^^^^^^ value used here after move

A box has one owner, and api took it. You could clone the Config, but you’d have two configurations diverging at the first change. You could lend &Config, but then you’d have to prove who lives longest, with lifetimes in every Service. When no owner is clearly “the last one”, what’s left is counting them.

Rc::clone adds an owner

let config = Rc::new(Config { nom: "prod".to_string() });
let api = Service { config: Rc::clone(&config) };
{
    let worker = Service { config: Rc::clone(&config) };
    println!("même valeur    : {}", Rc::ptr_eq(&api.config, &worker.config));
}
drop(config);
println!("lecture        : {}", api.config.nom);
drop(api);
println!("fin de main");
après new      : 1
après api      : 2
après worker   : 3
même valeur    : true
adresses       : 0x102f6d4d0 0x102f6d4d0
worker sorti   : 2
config lâché   : 1
lecture        : prod
Config libérée (prod)
fin de main

Rc::clone doesn’t touch the Config. It copies an 8-byte pointer and adds 1 to the counter stored next to the value:

 the stack                        the heap
┌────────────────┐
│ config       ●─┼──────┐      ┌──────────────────────┐
├────────────────┤      ├─────▶│ strong count: 3      │
│ api.config   ●─┼──────┤      ├──────────────────────┤
├────────────────┤      │      │ Config { nom: prod } │
│ worker.config●─┼──────┘      └──────────────────────┘
└────────────────┘                    0x…4d0
   8 B each

The rest is reading the output. worker leaves its scope: 2. drop(config) drops the original variable: 1, and the value stays readable through api, because no owner is the “real” one. drop(api): 0, and Drop frees the value, before “fin de main”.

With Box, the moment of release could be read in the code. With Rc, it depends on the order in which owners go away at runtime. That’s the price of sharing.

Shared, therefore read-only: E0596

let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
a.push(4);
error[E0596]: cannot borrow data in an `Rc` as mutable
 --> mutable.rs:6:5
  |
6 |     a.push(4);
  |     ^ cannot borrow as mutable
  |
  = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Vec<i32>>`

It’s the borrowing rule coming back: many readers, or a single writer. An Rc has several readers by construction, so it only hands out &T. Rc::make_mut respects the rule by cloning the value if it’s shared:

let mut a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
Rc::make_mut(&mut a).push(4);
[1, 2, 3, 4] [1, 2, 3]
même valeur : false

a got its own copy, b keeps the old one: that’s copy-on-write. For both to see the change, you need interior mutability, Rc<RefCell<T>>, the subject of the next issue.

Across threads: E0277, and Arc

let config = Rc::new(String::from("prod"));
let copie = Rc::clone(&config);
let h = thread::spawn(move || {
    println!("{copie}");
});
error[E0277]: `Rc<String>` cannot be sent between threads safely
   --> thread_rc.rs:7:27
    |
  7 |       let h = thread::spawn(move || {
    |               ------------- ^------
    |               |             |
    |  _____________|_____________within this `{closure@thread_rc.rs:7:27: 7:34}`
    | |             |
    | |             required by a bound introduced by this call
  8 | |         println!("{copie}");
  9 | |     });
    | |_____^ `Rc<String>` cannot be sent between threads safely
    |
    = help: within `{closure@thread_rc.rs:7:27: 7:34}`, the trait `Send` is not implemented for `Rc<String>`

An Rc’s counter is a plain integer. If two threads do +1 at the same instant, one of them can be lost: the counter reaches zero too early, and the value is freed while an owner is still reading it. Rust doesn’t let that program exist: thread::spawn requires what it’s given to be Send, and Rc isn’t. It’s a trait bound like any other, checked at compile time.

let config = Arc::new(String::from("prod"));
let copie = Arc::clone(&config);
let h = thread::spawn(move || {
    println!("dans le thread : {copie}, compteur {}", Arc::strong_count(&copie));
});
h.join().unwrap();
println!("après join     : compteur {}", Arc::strong_count(&config));
dans le thread : prod, compteur 2
après join     : compteur 1

Arc is the same model with an atomic counter: each +1 and each -1 is an indivisible operation, safe from several threads. Same interface, same size (8 bytes). The thread finishes, its copy goes away, the counter falls back to 1.

The cycle: the leak Rust doesn’t prevent

struct Noeud {
    nom: &'static str,
    autre: RefCell<Option<Rc<Noeud>>>,
}

let a = Rc::new(Noeud { nom: "a", autre: RefCell::new(None) });
let b = Rc::new(Noeud { nom: "b", autre: RefCell::new(Some(Rc::clone(&a))) });
*a.autre.borrow_mut() = Some(Rc::clone(&b));
println!("a : {} / b : {}", Rc::strong_count(&a), Rc::strong_count(&b));
println!("fin de main");
a : 2 / b : 2
fin de main

Noeud implements Drop and prints “libéré”. Nothing is printed. At the end of main, the variables a and b go away and each counter goes from 2 to 1: a is still owned by b, b by a.

        ┌──────── Rc ────────┐
        │                    ▼
   ┌─────────┐          ┌─────────┐
   │ Noeud a │          │ Noeud b │      counters: 1 and 1
   │ fort: 1 │          │ fort: 1 │      never 0, never freed
   └─────────┘          └─────────┘
        ▲                    │
        └──────── Rc ────────┘

The program compiles without a warning and breaks no guarantee: Rust promises you’ll never read invalid memory, not that you’ll give all memory back. Reference counting can’t see cycles.

Weak: knowing without owning

struct Noeud {
    nom: &'static str,
    enfant: RefCell<Option<Rc<Noeud>>>,
    parent: RefCell<Weak<Noeud>>,
}

*parent.enfant.borrow_mut() = Some(Rc::clone(&enfant));
*enfant.parent.borrow_mut() = Rc::downgrade(&parent);
parent : fort 1 faible 1
enfant : fort 2 faible 0
upgrade : parent
parent libéré
upgrade : personne
fin de main
enfant libéré

A Weak is a link that doesn’t count in the strong counter. The parent owns the child, the child merely knows its parent. The parent’s strong count stays at 1: drop(parent) frees it. Since the value may be gone, a Weak can’t be read directly: upgrade() returns an Option, Some while the parent lives, None afterwards. Absence is in the type.

The question to ask in front of a graph: who owns whom? Ownership links go one way (Rc), back links are Weaks.

What the picture hides

  • Rc::clone(&x) rather than x.clone(). Both do the same thing (counter at 2, ptr_eq true). The long form signals a cheap clone to the reader, not a deep copy.
  • Arc doesn’t make the content mutable. It only protects the counter. To write from several threads, you need a lock: Arc<Mutex<T>>.
  • Arc everywhere isn’t free. Atomic operations cost more than a +1. In a single thread, Rc is enough, and the compiler will warn you the day that stops being true.
  • Rc isn’t the first reflex. One owner and &T borrows are enough most of the time, with no counter and no allocation. Rc is for when no owner clearly outlives the others.
  • The counter lives on the heap, with the value. Rc<T>, Arc<T> and Weak<T> are 8 bytes on the stack; the strong and weak counters are stored next to the value.

Going further

Questions fréquentesFrequently asked questions

Que signifie « `Rc<String>` cannot be sent between threads safely » (E0277) ?What does "`Rc<String>` cannot be sent between threads safely" (E0277) mean?

Tu déplaces un Rc dans un autre thread, par exemple avec thread::spawn(move || …). Le compteur d'un Rc est un entier ordinaire : deux threads qui l'incrémentent en même temps peuvent le fausser, et la valeur serait libérée trop tôt ou jamais. Rc n'implémente donc pas Send, et rustc refuse à la compilation. Correctif : Arc, dont le compteur est atomique. Remplace Rc::new par Arc::new et Rc::clone par Arc::clone.You're moving an Rc into another thread, for instance with thread::spawn(move || …). An Rc's counter is a plain integer: two threads incrementing it at the same time can corrupt it, and the value would be freed too early or never. So Rc doesn't implement Send, and rustc refuses at compile time. Fix: Arc, whose counter is atomic. Replace Rc::new with Arc::new and Rc::clone with Arc::clone.

Quelle différence entre Rc et Arc ?What's the difference between Rc and Arc?

Le compteur. Celui de Rc est un entier simple, rapide, réservé à un seul thread. Celui d'Arc est atomique (Atomically Reference Counted) : il peut être mis à jour depuis plusieurs threads, au prix d'opérations un peu plus coûteuses. L'interface est la même et les deux font 8 octets. Prends Rc tant que tout reste dans un thread, Arc dès que la valeur en traverse un : le compilateur te le dira.The counter. Rc's is a plain integer, fast, reserved to a single thread. Arc's is atomic (Atomically Reference Counted): it can be updated from several threads, at the price of slightly more expensive operations. The interface is the same and both are 8 bytes. Use Rc as long as everything stays in one thread, Arc as soon as the value crosses one: the compiler will tell you.

Rc::clone copie-t-il la valeur ?Does Rc::clone copy the value?

Non. Rc::clone copie le pointeur (8 octets) et ajoute 1 au compteur ; la valeur n'est ni lue ni dupliquée. Vérifié : après deux Rc::clone, strong_count vaut 3, Rc::ptr_eq rend true et les adresses sont identiques. On écrit Rc::clone(&x) plutôt que x.clone() par convention, pour qu'un lecteur voie tout de suite qu'il s'agit d'un clone bon marché et non d'une copie profonde.No. Rc::clone copies the pointer (8 bytes) and adds 1 to the counter; the value is neither read nor duplicated. Checked: after two Rc::clone calls, strong_count is 3, Rc::ptr_eq returns true and the addresses are identical. By convention you write Rc::clone(&x) rather than x.clone(), so a reader sees right away that it's a cheap clone and not a deep copy.

Pourquoi « cannot borrow data in an `Rc` as mutable » (E0596) ?Why "cannot borrow data in an `Rc` as mutable" (E0596)?

Parce qu'une valeur partagée ne peut pas être modifiée librement : plusieurs propriétaires la lisent, et une écriture par l'un d'eux violerait la règle « plusieurs lecteurs ou un seul écrivain ». Rc ne donne donc que des accès en lecture (il n'implémente pas DerefMut). Deux sorties : Rc::make_mut, qui clone la valeur si elle est partagée avant de la modifier, ou la mutabilité intérieure avec Rc<RefCell<T>>.Because a shared value can't be freely modified: several owners read it, and a write by one of them would break the "many readers or one writer" rule. So Rc only gives read access (it doesn't implement DerefMut). Two ways out: Rc::make_mut, which clones the value if it's shared before modifying it, or interior mutability with Rc<RefCell<T>>.

Rust peut-il avoir des fuites mémoire ?Can Rust leak memory?

Oui, et en code sûr. Deux Rc qui se pointent l'un l'autre forment un cycle : chacun garde le compteur de l'autre à 1, il ne retombe jamais à zéro, et aucun Drop ne s'exécute. Rust garantit l'absence d'accès mémoire invalide, pas l'absence de fuite. L'issue est Weak : un lien qui ne compte pas dans le compteur fort. Le parent possède l'enfant par Rc, l'enfant connaît son parent par Weak, et lit à travers upgrade(), qui rend une Option.Yes, and in safe code. Two Rcs pointing at each other form a cycle: each keeps the other's counter at 1, it never falls back to zero, and no Drop runs. Rust guarantees the absence of invalid memory access, not the absence of leaks. The way out is Weak: a link that doesn't count in the strong counter. The parent owns the child through Rc, the child knows its parent through Weak, and reads through upgrade(), which returns an Option.

RustRcArcSmart pointersE0277Modèle mental

← Tous les articlesAll articles