So can unique_ptr be used safely in stl collections?
Posted
by DanDan
on Stack Overflow
See other posts from Stack Overflow
or by DanDan
Published on 2010-05-20T18:17:14Z
Indexed on
2010/05/20
18:20 UTC
Read the original article
Hit count: 449
I am confused with unique_ptr and rvalue move philosophy.
Let's say we have two collections:
std::vector<std::auto_ptr<int>> autoCollection;
std::vector<std::unique_ptr<int>> uniqueCollection;
Now I would expect the following to fail, as there is no telling what the algorithm is doing internally and maybe making internal pivot copies and the like, thus ripping away ownership from the auto_ptr:
std::sort(autoCollection.begin(), autoCollection.end());
I get this. And the compiler rightly disallows this happening.
But then I do this:
std::sort(uniqueCollection.begin(), uniqueCollection.end());
And this compiles. And I do not understand why. I did not think unique_ptrs could be copied. Does this mean a pivot value cannot be taken, so the sort is less efficient? Or is this pivot actually a move, which in fact is as dangerous as the collection of auto_ptrs, and should be disallowed by the compiler?
I think I am missing some crucial piece of information, so I eagerly await someone to supply me with the aha! moment.
© Stack Overflow or respective owner