c++ - 为什么在 C++11 中更改了 std::vector::resize 签名?

标签 c++ c++11 vector stl resize

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, 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.

旧的 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/

相关文章:

c++ - 这是从单例类派生的标准方法吗?

c++ - VisualStudio优化编译器版本19.00.23506.0中的明显编译错误

c++ - 如何让我的程序正确地将数据传递到我的阵列? (家庭作业)

c++ - 连续枚举C++ 11

c++ - 对 map<string, vector<string>> 中的唯一值进行排序

c++ - SSE 的条件语句

c++ - 如何获取进程中使用的 .DLL 的(物理)基地址?

c++ - Lambda 捕获 'this' 保存为 std::function

java - 什么函数可以用来对 vector 进行排序?

c++ - vector - 当元素有 const 成员时交换两个元素