Could the assign function for containers possibly overflow?
I ran into this question today and thought I should post it for the community's reference and/or opinions.
The standard C++ containers vector, deque, list, and string provide an assign
member function. There are two versions; I'm primarily interested in the one accepting an iterator range. The Josuttis book is a little ambiguous with its description. From p. 237...
Assigns all elements of the range [beg,end); this is, is replaces all existing elements with开发者_运维知识库 copies of the elements of [beg,end).
It doesn't say what happens if the size of the assignee container is different from the range being assigned. Does it truncate? Does it automagically expand? Is it undefined behavior?
Here's what I found. It turns out I didn't have to worry about silently doing the wrong thing. Once again, the standard has the answer. From section 23.2.6.1:
void assign(Iter first, Iter last);
Effects:
erase(begin(), end());
insert(begin(), first, last);
So it's really just a shortcut for a clear()
followed by an insert
of the full range.
精彩评论