So can unique_ptr be used safely in stl collections?

后端 未结 3 438
南笙
南笙 2020-11-29 01:33

I am confused with unique_ptr and rvalue move philosophy.

Let\'s say we have two collections:

std::vector> autoCollect         


        
3条回答
  •  攒了一身酷
    2020-11-29 01:57

    std::sort could work only with move operations and no copying, as long as there is only one live copy of each object at any given time. This is a weaker requirement than working in-place, since in principle you could allocate another array temporarily and move all objects to while reordering them.

    for example with std::vector> exceeding its capacity, it allocates storage for a larger vector and then moves all objects from old storage to the new one. This is not an in-place operation but it's perfectly valid.

    As it turns out, sorting algorithms like quick-sort and heap-sort can in fact work in-place without difficulty. quick-sort's partition routine uses std::swap internally, which counts as a move operation for both objects involved. When selecting a pivot, one trick is to swap it with the first element in the range, this way it will never be moved until partitioning is finished.

提交回复
热议问题