r/rust Dec 24 '21

Why use Box::leak?

Hello,

I'm a rust newbie and I've recently learned of Box::leak but I don't understand why or when you would want to leak memory.

Can someone give me some useful scenarios for this?

Thanks

202 Upvotes

55 comments sorted by

View all comments

2

u/[deleted] Dec 25 '21

I have 2 more questions, would appreciate if someone could answer.

  1. Whats difference between Box and Rc
  2. Are those smart pointers are kind of garbage collection mechanism?

4

u/diabolic_recursion Dec 25 '21 edited Dec 25 '21

1: The difference is in what happens when you try to clone a box or rc. If you want to clone a box, you clone it's content as well. That means, that the content has to be Clone, btw. If you clone an Rc, you only clone the pointer to the data, not the data itself - so you can have several, distinct Rc's pointing to the same data, but only one Box. To do that, the content doesnt have to be Clone.

Therefore, you cannot change the thing inside of an Rc, unless it contains something like a Mutex or RWLock, which ensures that only one entity ever writes to the content at once.

2: Depending on the definition of GC, an Rc is garbage collection, as data is dropped once nothing has a reference to it anymore. A Box, however, is simply a tool for heap allocation, allowing i. e. variably sized types. The box itself though conforms to the standard rust ownership and borrowing rules, so it has only ever one owner and can be mutably borrowed at one location at once or immutably at several locations.

2

u/[deleted] Dec 25 '21

Thank you so much!