咚咚,查看cocos2dx3.2引擎关于内存管理部分,看到这个:
PoolManager::PoolManager()
{
_releasePoolStack.reserve(10);
}
std::vector<AutoreleasePool*> _releasePoolStack;
百度下:具体参考http://www.cnblogs.com/qlee/archive/2011/05/16/2048026.html
vector 的reserve增加了vector的capacity,但是它的size没有改变!而resize改变了vector的capacity同时也增加了它的size!
原因如下:
reserve是容器预留空间,但在空间内不真正创建元素对象,所以在没有添加新的对象之前,不能引用容器内的元素。加入新的元素时,要调用push_back()/insert()函数。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<int> data;
data.reserve(10);
data.push_back(10);
data.push_back(12);
data.push_back(13);
data.push_back(14);
data.push_back(15);
cout << data.size() << " " << data.capacity() << endl;
for (int i = 0; i < data.capacity(); ++i) {
cout << data[i] << endl;
}
data.clear();
cout << data.size() << " " << data.capacity() << endl;
data.resize(20);
cout << data.size() << " " << data.capacity() << endl;
data.push_back(16);
data.push_back(17);
cout << data.size() << " " << data.capacity() << endl;
for (int i = 0; i < data.capacity(); ++i) {
cout << data[i] << endl;
}
return 0;
}
结果如下:
5 10
10
12
13
14
15
0
0
0
0
0
0 10
20 20
22 40
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
16
17
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Program ended with exit code: 0
从结果看出,确实 resize和reserve都不好覆盖原来动数据