std::vector::resize
从 pre-C++11 的变化背后的原因是什么:
void resize( size_type count, T value = T() );
到兼容的 C++11 形式:
void resize( size_type count );
void resize( size_type count, const value_type& value);
最佳答案
C++11 标准附录 C(兼容性)的 C.2.12 段规定:
Change: Signature changes:
resize
Rationale: Performance, compatibility with move semantics.
Effect on original feature: For
vector
,deque
, andlist
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.
旧的 resize()
函数是从 value
复制构造新元素。这使得当 vector 的元素是默认可构造但不可复制(您可能希望稍后移动分配它们)时,无法使用 resize()
。这解释了“与移动语义的兼容性”的基本原理。
此外,如果您不希望出现任何拷贝,则可能会很慢,只希望默认构造新元素。此外,value
参数在 C++03 版本中是按值传递的,这会产生不必要的拷贝 (as mentioned by TemplateRex in his answer) 的开销。这解释了“性能”的基本原理。
关于c++ - 为什么在 C++11 中更改了 std::vector::resize 签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17002690/