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