Hacker News new | ask | show | jobs
by crispweed 3127 days ago
> The most important thing about Rust (and the thing that makes programming in Rust confusing) is that it needs to decide at compile time when all the memory in the program needs to be freed.

> ...

> When the function blah returns, x goes out of scope, and we need to figure out what to do with its my_cool_pointer member. But how can Rust know what kind of reference my_cool_pointer is? Is it on the heap?

> ...

> If we knew that my_cool_pointer was allocated on the heap, then we would know what to do when it goes out of scope: free it!

The way this is written kind of seems to suggest that Rust will sometimes free heap memory when a reference to that memory goes out of scope, which I think is misleading.

As I understand it, this is not the case, and the point is just that Rust needs to be able to prove that nothing else freed the referenced heap memory at any point where the reference may be used.

2 comments

No, I think the article is right. When a value goes out of scope, its drop method is called, which for Box values deallocates it.

The trick is that if it is (possibly) returned from a function, it is moved instead of dropped.

It's also important to distinguish Box from Rc. Both are heap values but have very different behavior.

The text I quoted seemed to suggest that the reference going out of scope could trigger deallocation.
Which is true.

The word "reference" is overloaded, it can be used to mean "anything pointery that's guaranteed to exist" too. Box<T> in this context is a reference.

The post does kind of dance between definitions of "reference" a bit, but I think that's intentional.

Yeah. Knowing that it's on the heap isn't enough - we also have to know whether we own it or are borrowing it.