Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

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

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...