开发者

Why does std::vector::resize(n, src) pass by value?

Pretty much as per the title.

The spec for std::vector<T>::resize seems to require that the src object be passed by value:

void resize(size_type n, T src = T() );

Why isn't a reference to a constant object used here instead?

void resize(size_type n, T const& src = T() );

For instance, in this question, the pass-by-value aspect appears to cause stackoverflow issues, due to the creation of a temporary object on the stack.

开发者_如何学C

If a reference to src was passed instead, we'd at least be able to workaround the issue by allocating a temporary on the heap which is passed-by-reference to ::resize().

It also seems that ::resize() is out of step with the other member functions for std::vector. For instance, the constructors take a src object by const& as expected:

vector (size_type n, T const& src = T(), Allocator const& = Allocator() );

EDIT: I dug out the c++03 standard and double checked that the function prototypes above are not mis-quoted...


It was a mistake in the Standard Library specification. It is fixed in C++11; std::vector now has two resize member functions declared as:

void resize(size_type sz);
void resize(size_type sz, const T& c);

The difference between the two is that if the size of the container is larger after the resize, the first overload value initializes the new elements, while the second copy constructs them; this pattern is used for other member functions and in other containers too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜