Rust

Rust

Made by DeepSource

Insertion of pointer to non-owned reference counted value into vector RS-W1106

Bug risk
Major

Pushing a pointer to a non-owned reference counted value into a vector will affect the clean-up of the value and bind it to the lifetime of the vector. This may be hard to realise from looking at the definition of the ref counted value, hence consider putting only "owned" reference counted values into the vector and then taking a handle to the pointed value as a reference.

Bad practice

let mut v = Vec::new();
let rcp = Rc::new(10);
v.push(rcp.clone());
v.insert(0, rcp.clone());

Recommended

let mut v = Vec::new();
// makes it obvious what the lifetime of the value is tied to
v.push(Rc::new(10));
let rcp = v[0].clone();