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
198 views
in Technique[技术] by (71.8m points)

c++ - What does the standard say about how calling clear on a vector changes the capacity?

This website implies that clearing a vector MAY change the capacity:

http://en.cppreference.com/w/cpp/container/vector/clear

Many implementations will not release allocated memory after a call to clear(), effectively leaving the capacity() of the vector unchanged.

But according to @JamesKanze this is wrong and the standard mandates that clear will not change capacity.

What does the standard say?

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

Depending on the version of the standard you are looking at, clear is defined as the equivalent of erase(begin(), end()), or (in C++11):
"Destroys all elements in a. Invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator."

In neither case is it allowed to modify the capacity; the following code is guaranteed safe by the standard:

std::vector<int> v;
for (int i = 0; i != 5; ++ i) {
    v.push_back(i);
}
assert(v.capacity() >= 5);
v.clear();
assert(v.capacity() >= 5);
v.push_back(10);
v.push_back(11);
std::vector<int>::iterator i = v.begin() + 1;
v.push_back(12);
v.push_back(13);
*i = 42;        //  i must still be valid, because none of 
                //  the push_back would have required an
                //  increase of capacity

(The reason for the change in wording in C++11: the committee didn't want to require MoveAssignable for clear, which would have been the case if it were defined in terms of erase.)


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

...