Why has the std::vector::resize signature been changed in C++11?

后端 未结 2 1967
天涯浪人
天涯浪人 2020-12-17 07:45

What are the reasons behind the change in std::vector::resize from the pre-C++11:

void resize( size_type count, T value = T() );
2条回答
  •  旧时难觅i
    2020-12-17 08:04

    Paragraph C.2.12 of the Annex C (Compatibility) to the C++11 Standard specifies:

    Change: Signature changes: resize

    Rationale: Performance, compatibility with move semantics.

    Effect on original feature: For vector, deque, and list the fill value passed to resize is now passed by reference instead of by value, and an additional overload of resize has been added. Valid C++ 2003 code that uses this function may fail to compile with this International Standard.

    The old resize() function was copy-constructing new elements from value. This makes it impossible to use resize() when the elements of the vector are default-constructible but non-copyable (you may want to move-assign them later on). This explains the "Compatibility with move semantics" rationale.

    Moreover, it may be slow if you do not want any copy to occur, just new elements to be default-constructed. Also, the value parameter is passed by value in the C++03 version, which incurs in the overhead of an unnecessary copy (as mentioned by TemplateRex in his answer). This explains the "Performance" rationale.

提交回复
热议问题