Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating std::vector of nonmovable type

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.

like image 964
RiaD Avatar asked Sep 11 '25 05:09

RiaD


1 Answers

You can:

  • Have a 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.)
  • Use deque<T> which does not require movability for emplace_back (although you lose Contiguity)
  • Write your own dynamic array that is roughly equivalent to a pair<unique_ptr<T[]>, size_t> that just allocates space for n Ts 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.

like image 180
Barry Avatar answered Sep 13 '25 19:09

Barry