Open
Description
It's common in game development to want fine-grained control of where values are allocated. This would commonly be used in object pools/ECS systems.
Support for this used to exist, but was removed. The reasons are summarized here: rust-lang/rust#27779 (comment)
Possibly oversimplified, the conventional/expected new() syntax does not accept a &self, constructing explicitly always goes to the stack (i.e. TheType { a: 1, b: 2}
), and neither of these allows for the allocation to fail. So it's unclear how this would be implemented in a way that is reliable.
I do not see any recent activity working on this.
It is possible in some cases that the optimizer would optimize away the stack temporary being copied to a heap address, but:
- It would never occur in debug
- It's quite a difficult optimization, in many cases requiring LTO. It couldn't be relied upon.
Some workarounds:
MaybeUninit
and unsafe code.- Use unconventional ways of construction i.e.
init(&mut self)
- Carefully structuring code to make it highly likely the optimizations will be taken (i.e.
container.push_with(|| TheType {a: 1, b: 1}
) - Crates can help with this. A couple different approaches: