Is shrink_to_fit the proper way of reducing the capacity a `std::vector` to its size?

后端 未结 3 1795
终归单人心
终归单人心 2020-12-05 05:01

In C++11 shrink_to_fit was introduce to complement certain STL containers (e.g., std::vector, std::deque, std::string). <

3条回答
  •  一整个雨季
    2020-12-05 05:13

    • If yes, what's the proper way of shrinking an STL container's capacity to its size (at least for std::vector).

    The 'swap trick' will trim a vector to the exact size required (from More Effective SQL):

    vector(persons).swap(persons);
    

    Particularly useful when the vector is empty, to release all memory:

    vector().swap(persons);
    

    Vectors were constantly tripping my unit tester's memory leak detection code because of retained allocations of unused space, and this sorted them out perfectly.

    This is the kind of example where I really don't care about runtime efficiency (size or speed), but I do care about exact memory usage.

    • And if there's a better way to shrink a container, what's the reason for the existence of shrink_to_fit after-all?

    I really don't know what the point of providing a function that can legally do absolutely nothing is. I cheered when I saw it had been introduced, then despaired when I found it couldn't be relied upon.

    Perhaps we'll see maybe_sort() in the next version.

提交回复
热议问题