-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Placement New #48
Comments
There is a bit of support that landed in the compiler: rust-lang/rust#62451 |
That change looks like a targeted approach to avoid a stack-to-heap copy into a newly constructed Box/Rc/Arc, rather than a general solution to put a value into a specific place in memory. It also requires unsafe code to use for every construction. (Understandable, even if not ideal, given that this is a low-level, uncommon thing to do.) One option we've discussed in the bi-weekly meeting was to have some sort of function that takes a pointer or MaybeUninit as an input and returns a T as output. It may be possible for the compiler to verify that all fields have been initialized to something. This would move one class of errors to being caught at compile time. The common case that generally has me reaching for placement new is implementing an object pool. So perhaps helpful guidance here for myself and others wanting placement new would be to simply use an existing object pool crate or implement it yourself with unsafe code. |
Sounds like it would be covered by VecHelper to some extent. |
Currently, there is a discussion on Zulip about placement new. |
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:
Some workarounds:
MaybeUninit
and unsafe code.init(&mut self)
container.push_with(|| TheType {a: 1, b: 1}
)The text was updated successfully, but these errors were encountered: