I had two matching vectors of unique_ptr
. I decided to unify them by making one vector of structs containing two unique_ptr
(the struct will also contain other items, eventually, hence this refactoring).
What is the best approach for me to add new items in this vector?
My current code is
std::vector<DestinationObjects> destinations;
for (unsigned short &id: ids) {
DestinationObjects d;
d.transmitter = unique_ptr<Transmitter> (new Transmitter(id));
d.controller = unique_ptr<Controller> (new Controller(id));
destinations.push_back(d);
}
Of course this copies d
, causing issues with unique_ptr
. What is the best approach to fixing this?
Options I can conceive of, some of which I am not sure will work:
- Just switch to
shared_ptr
. (A simple find-replace, but feels like a cop-out). - Write a move constructor for the struct that moves the unique_ptr. (Another thing to maintain that could go wrong, as I expand the struct).
- Push back an empty struct instance with null pointers for the unique_ptr and edit these in place once in the vector. (Fiddly syntax. Also I'm not sure this would even work).
Any ideas what would be another approach? Or why I should prefer one of the ones I have listed?