In this code...
struct Test { a: i32, b: i64 }
fn foo() -> Box<Test> { // Stack frame:
let v = Test { a: 123, b: 456 }; // 12 bytes
Box::new(v) // `usize` bytes (`*const T` in `Box`)
}
... as far as I understand (ignoring possible optimizations), v
gets allocated on the stack and then copied to the heap, before being returned in a Box
.
And this code...
fn foo() -> Box<Test> {
Box::new(Test { a: 123, b: 456 })
}
...shouldn't be any different, presumably, since there should be a temporary variable for struct allocation (assuming compiler doesn't have any special semantics for the instantiation expression inside Box::new()
).
I've found Do values in return position always get allocated in the parents stack frame or receiving Box?. Regarding my specific question, it only proposes the experimental box
syntax, but mostly talks about compiler optimizations (copy elision).
So my question remains: using stable Rust, how does one allocate struct
s directly on the heap, without relying on compiler optimizations?
Anything inside a Box , Vec , Rc , or Arc will be put on the heap, but the actual Box struct itself (i.e. the pointer) will live on the stack.
Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.
Dynamic memory allocation and deallocation are very slow operations when compared to automatic memory allocation and deallocation. In other words, the heap is much slower than the stack.
Is there a way to allocate directly to the heap without
box
?
No. If there was, it wouldn't need a language change.
People tend to avoid this by using the unstable syntax indirectly, such as by using one of the standard containers which, in turn, uses it internally.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With