为什么在C ++ 11中改变了std :: vector :: resize签名? [英] Why has the std::vector::resize signature been changed in C++11?
问题描述
std :: vector :: resize
从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到C ++ 11标准规定:
:签名更改: resize
:性能,与移动语义的兼容性。
对原始功能的影响:矢量
, deque
和 list
,传递给resize的填充值现在由
引用而不是通过值传递,并且添加了resize的额外重载。使用此函数的有效C ++ 2003代码
可能无法使用此国际标准编译。
旧 resize()
函数是从 value
中复制构造新元素。这使得当向量的元素是默认可构造但不可复制的(你可能想移动 - 稍后分配它们)时,不可能使用 resize()
。这解释了
移动语义兼容性的原因。
此外,如果您不想发生任何复制,可能会很慢新元素被默认构造。此外, value
参数通过C ++ 03版本中的值传递,这会导致不必要的副本的开销()。这解释了效果的基本原理。
What are the reasons behind the change in std::vector::resize
from the pre-C++11:
void resize( size_type count, T value = T() );
to the compatible C++11 form:
void resize( size_type count );
void resize( size_type count, const value_type& value);
解决方案 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.
这篇关于为什么在C ++ 11中改变了std :: vector :: resize签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!