3 ms·
> Here, r is on the stack (or in a register), but is pointing to something on the heap, so "&T is heap allocated" feels wrong. What's the difference between `r
by littlestymaar 9y ago
> Here, r is on the stack (or in a register), but is pointing to something on the heap, so "&T is heap allocated" feels wrong.
What's the difference between `r` and `b` here ? (no pun intended)
- steveklabnik 9y agoThey both point to the same place. However, r doesn't have ownership, so when r goes out of scope, the memory won't be freed. However, b does, and so when b goes out of scope, the memory will be freed.
- littlestymaar 9y agook, but how does it link to where the value is allocated ? My question was, is it wrong to say that `b` isn't heap allocated either since : «Here, b is on the stack (or in a register), but is pointing to something on the heap.»
- steveklabnik 9y agoIt's wrong to say that b isn't heap allocated because it's not stored on the heap. &Ts can refer to something anywhere, heap or stack, and can also be anywhere, heap or stack. A Box<&i32> is going to have a &T on the heap.
- Crespyl 9y agoThey are both pointers, but `b` is an owned pointer (it "owns" a heap allocated value) and `r` is a borrowed/reference pointer (a "pure" reference to something (heap or stack) that it doesn't own and isn't responsible for). `b` cannot be moved, mutated, or deallocated until `r` is gone. When `b` goes out of scope the heap value it points to will be automatically deallocated, unless `r` still exists somewhere (saved off in a struct for example), in which case the program won't compile.