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:
shared_ptr. (A simple find-replace, but feels like a cop-out).Any ideas what would be another approach? Or why I should prefer one of the ones I have listed?
Simpley do a vec.emplace_back( std::move(d) ).
If (as mentioned in your comment) your compiler does not implement implicit move construtors, write your own move constructor. My advice in the future is whenever you have a problem with any C++11 feature and are asking a question, mention that you are using this compiler, as there is a pretty good chance that it's "C++11 support" will be an important issue.
If your compiler does not support any move constructor at all, stop using unique_ptr -- they are rather useless without move constructors. ;)
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