Search code examples
c++stdvectormove-semantics

Resizing a std::vector using move insertion and copy insertion


In the C++ standard vector.capacity section, it defines two overloads for resize(). (see also https://en.cppreference.com/w/cpp/container/vector/resize)

This overload requires that the type T is MoveInsertable and DefaultInsertable:

constexpr void resize(size_type sz);

The other overload requires that the type T is CopyInsertable:

constexpr void resize(size_type sz, const T& c);

My question is that why doesn't the second overload try to move from the existing values from the old vector, and further copy-insert new values from the supplied c argument. Wouldn't that be more efficient?


Solution

  • I agree that the second parameter could be an rvalue reference - this saves one copy, when it is subsequently copied from the first newly appended item. I assume what you have in mind is something like this:

    std::vector<LargeObject> v;
    
    // ...
    
    LargeObject obj = setupLotsOfResources();
    
    // Now do 1 move and 9 copies instead of 10 copies
    v.resize(10, std::move(obj));
    

    However, I would consider this an edge case, and working with rvalue references that are used for 1 move construction and N-1 copies is quite a confusing API. As you are free to use the std::vector API with what is already there such that for the above example, you will have 1 move and N-1 copies, I believe the rationale behind the existing function signature is ease of use and a straightforward signature that doesn't require much studying of the specs to understand what it does.