-
Notifications
You must be signed in to change notification settings - Fork 131
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
Add "placement new"-like constructor API #277
Comments
If this feature request is accepted, I can provide PR implementing it. |
Does this still happen with |
As far as I know Rust may optimize out Enabling optimizations for debug builds is also not an option, when I want to create a library. |
The use case you brought up in the original case is probably not the whole story, but for that specific case, I think a |
I think the idea sounds good. It was long used that |
If we're placement new'ing, any input on best shape of api here: #278 ? |
Feature description
Add new constructors to
ArrayVec
andArrayString
, that instead of returning initializedSelf
, write to user-provided out-pointer.Rationale
Consider following case. I want to use a heap allocated
Vec
-like structure, but withconst
-known maximum capacity. I would like to useBox<ArrayVec<T, N>>
as a backing storage. However creating such type is problematic. For sufficiently bigN
expressionBox::new(ArrayVec::new())
may overflow stack.Box
(and other types in standard library) have currently unstable (but stable in current beta, which will hit stable in 3 days) APInew_uninit
that helps to solve this exact case. Howeverarrayvec
does not have any API that would allow constructing its types in-place, which makes it impossible to safely use aforementioned std APIs. By adding this kind of constructors,ArrayVec
becomes usable in described scenario (and others that require in-place initialization).Drawbacks
unsafe
code. While it wouldn't be very difficult one, it will require more attention when doing possible internal refactors.Other possibilities
One possibility is to just do nothing. Users who wish to use placement-new-like constructors can just re-implement
ArrayVec
manually.There is also a dark and unsafe way. Since
ArrayVec
has#[repr(C)]
, one can create their own mirror type, initialize it, and thenstd::mem::transmute
it intoarrayvec::ArrayVec
. I think it requires no further explanation why this should not be preferred by anyone. :)Third possibility would be to make
ArrayVec
's fields public, which would allow users to instantiate it how they wish. I do not want to endorse this, just mention it for the sake of completeness.Possible implementation
Here is a possible implementation:
It could be used like this:
Open questions
&mut MaybeUninit<Self>
,*mut Self
or something different?unsafe
? It should be sound anyway, but maybe it would be better that user thinks twice before calling it.Drop
on contained value?The text was updated successfully, but these errors were encountered: