Moving unique_ptrs from one vector to another

rubenvb picture rubenvb · Apr 26, 2011 · Viewed 9k times · Source

I'd like to move the unique_ptr's stored in an unsorted vector of them to another vector, that will contain the sorted vector of pointers.

Surely moving a unique_ptr will not automatically erase the element in the first vector? How can I do this?

Example of what I want to do:

std::vector<std::unique_ptr<T> > unsorted, sorted;
// fill the "unsorted" vector
while( unsorted.size() > 0 )
{
    const auto it = find_next_element_to_add_to_sorted(unsorted);
    sorted.push_back( std::move(*it) );
}

I hope the intent is clear.

UPDATE: my algorithm does not allow sorting in-place. If anyone is feeling nice today (I am not asking, see above for my question), feel free to implement it for this situation and show me. I really need the "sort by move". And I don't really see why the moving would be that much more expensive.

Answer

Howard Hinnant picture Howard Hinnant · Apr 26, 2011

Your code looks basically correct to me, except that it seems like you intend for the moved-from unique_ptr to be erased from the unsorted vector:

std::vector<std::unique_ptr<T> > unsorted, sorted;
// fill the "unsorted" vector
while( unsorted.size() > 0 )
{
    const auto it = find_next_element_to_add_to_sorted(unsorted);
    sorted.push_back( std::move(*it) );
    unsorted.erase(it);
}

After the move it refers to a moved-from unique_ptr and *it == nullptr. It still exists in unsorted and if that is not desired, must be explicitly erased.