C++ STL载体储备
我用下面的代码对 stl 矢量进行了测试:
struct structA{
char charArray[256];
}
structA a;
..assign 256 characters to a.charArray
vector<structA> v1;
v1.reserve(1000);
for(int i=0; i<1000; i++){
v1.push_back(a);
}
我意识到每 16 个 Push_back,v1.push_back 中就会出现一个尖峰。我怀疑内存被重新分配。我想知道为什么会这样,因为我已经使用了储备?我尝试使用 vectorv1(1000) 声明向量,它也给出了相同的行为。
顺便说一句,如果我将字符增加到 512,则只需要 8 个 Push_back,8 * 512 提供大约 4k 内存。该问题与内存分页有关吗?
谢谢。
I have tested on stl vector with code below:
struct structA{
char charArray[256];
}
structA a;
..assign 256 characters to a.charArray
vector<structA> v1;
v1.reserve(1000);
for(int i=0; i<1000; i++){
v1.push_back(a);
}
I realized that for every 16 push_back, there is a spike in the v1.push_back. I suspect that there is a reallocation of memory. I am wondering why is it so since I already use the reserve? I tried to declared the vector using vectorv1(1000), it also gives the same behaviour.
By the way, if I increase the char into 512, it took just 8 push_back, 8 * 512 gives around 4k memory. Would that the issue related to memory paging?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
运行这个简单的测试,看看是否有任何您不想要或不期望的分配或释放。
Run this simple test and see if there are any allocations or deallocations you don't want or don't expect.
最好的办法是启动调试器并“步入”reserve,看看那里发生了什么 - 也许您的 STL 实现对
reserve()
没有任何作用。进入push_back()
也不会造成任何伤害 - 这样您就会确切地知道发生了什么。Your best bet is to fire up the debugger and "step into" reserve and see what's going on there - maybe your implementation of STL does nothing on
reserve()
. Stepping intopush_back()
won't hurt either - this way you will know exactly what's going one.