4 ms·
> `Vec`, `String`, `Box`, `Rc`, and `Arc` are all heap allocated and that slices, arrays, `str`, `&T`, and `&mut T` are not. if T is Box<u32>, &T is heap alloc
by littlestymaar 9y ago
> `Vec`, `String`, `Box`, `Rc`, and `Arc` are all heap allocated and that slices, arrays, `str`, `&T`, and `&mut T` are not.
if T is Box<u32>, &T is heap allocated. Imho, it's more accurate to say that `&` and `&mut` doesn't cause heap allocation. </nitpick>
- steveklabnik 9y agoWith pointers, you have to differentiate where the pointer is from where the pointer is pointing to is. let b = Box::new(5); let r = &*b; 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.
- 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.
- saghm 9y agoAs I mentioned in a couple sibling comments, it looks I didn't do a great job explaining what I meant here, but my basic point was that if I want to optimize my program by minimizing heap allocations, I can ignore all `&str`, `&[T]`, `&T`, etc. and just focus on `Vec`, `String`, `Box`, etc. In Go, there isn't any clear boundary like this, so I'm forced to reason about every slice and pointer to determine if they're doing heap allocations or not.