![](/img/trans.png)
[英]Does the standard say anything about coexistence of exceptions and different calling conventions?
[英]What does the standard say about how calling clear on a vector changes the capacity?
本網站暗示清除向量可能會改變容量:
http://en.cppreference.com/w/cpp/container/vector/clear
許多實現在調用clear()之后不會釋放已分配的內存,從而有效地保持向量的容量()不變。
但根據@JamesKanze的說法,這是錯誤的,標准要求明確不會改變容量。
標准說什么?
根據您正在查看的標准版本, clear
定義為erase(begin(), end())
或(在C ++ 11中)的等效項:
“銷毀a中的所有元素。使所有引用,指針和迭代器無效,引用a的元素,並可能使過去的迭代器無效。”
在任何情況下都不允許修改容量; 以下代碼保證標准安全:
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
(在C ++ 11中改變措辭的原因是:委員會不希望要求MoveAssignable
clear
,如果它是根據erase
定義的話就是這種情況。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.