I have a std::vector
named args
(I don’t know the size of the vector at compile time) and a non movable type NonMoveable
.
I want to create a vector of the same size as args, so that it equals to
{NonMovable(args[0], additional_arg), NonMovable(args[1], additional_arg), …, NonMovable(args.back(), additional_arg)}
I don’t need to change the size of the vector later. How do I do that?
I can’t reserve()
then emplace_back()
because emplace_back()
requires moving (to allow reallocation which is not possible in my case)
I do not want to use std::list
because it is not contiguous.
You can:
vector<unique_ptr<T>>
or vector<optional<T>>
or vector<some_other_defer_storage_mechanism<T>>
instead of just vector<T>
- these are all wrapper types that adding some functionality T
without affecting T
(unique_ptr<T>
makes it movable, optional<T>
ensures default construction so you can construct with the right size then emplace()
within the optional
, etc.)deque<T>
which does not require movability for emplace_back
(although you lose Contiguity)pair<unique_ptr<T[]>, size_t>
that just allocates space for n
T
s and then placement-news onto each of them, ensuring that destruction does the right thing. This isn't so bad to implement - since you won't be changing the size, you need to support a very minimal amount of overall operations.Whichever one of these is the best answer really depends.
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