Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding struct items containing a unique_ptr to an stl container

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:

  1. Just switch to shared_ptr. (A simple find-replace, but feels like a cop-out).
  2. 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).
  3. 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?

like image 953
rod Avatar asked Mar 25 '26 00:03

rod


1 Answers

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. ;)

like image 127
Yakk - Adam Nevraumont Avatar answered Mar 26 '26 13:03

Yakk - Adam Nevraumont