Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving unique_ptrs from one vector to another

Tags:

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.

like image 968
rubenvb Avatar asked Apr 26 '11 15:04

rubenvb


People also ask

Can you move a unique_ ptr?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.

What is unique_ ptr in c++?

> class unique_ptr<T[], Deleter>; (2) (since C++11) std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope.

How does unique_ ptr work?

A unique_ptr object wraps around a raw pointer and its responsible for its lifetime. When this object is destructed then in its destructor it deletes the associated raw pointer. unique_ptr has its -> and * operator overloaded, so it can be used similar to normal pointer.


1 Answers

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.

like image 146
Howard Hinnant Avatar answered Sep 29 '22 16:09

Howard Hinnant