Azo*_*ous 1 c++ memory-leaks stl vector
请考虑以下代码段:
std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);
v.erase(v.begin(), v.end());
std::cout << v.capacity << std::endl;
Run Code Online (Sandbox Code Playgroud)
打印出来100.这是否意味着向量仍然保留了100个内存位置?是否需要reserve(0)在调用erase(begin,end)向量后调用,以放弃向量所持有的所有空间?
如果容量为100,vector则为100个元素分配空间.reserve(0)是一种无操作,因为reserve不会缩小容量.
reserve(n)将尝试将分配增加到至少 n元素的足够空间.不能保证它会成功,它不会报告失败并且可能会过度分配.
reserve除非你使用和不使用它来测量你的代码,否则不要打电话,发现它有很大的不同.所有其他用途reserve都是过早优化.