Sever开发者一般不是非常喜欢用STL容器来管理内存数据,原因可能是STL容器的内存回收策略未必非常适合Server:Server常驻内存,非常希望用过的内容能够很快的回收。
使用vector的push_back 插入10000个对象后,在吧这10000个对象pop_back出去,申请的10000个对象的内存空间实际上并没有立刻释放掉。STL容器仍然保留这部分对象以备后续使用。
如果确实需要紧缩空vector的内存,可以使用vector的swap方法。
如vector A为需要紧缩的容器,可以建立一个临时的vector B, 调用B.swap(A).
因为B为临时对象,可以立即释放,而A和B的内容交换了,即A是B。达到了内存紧缩的目的。
附上代码一段:

#include <vector>

#include <iostream>
using namespace std;

typedef
struct Block{
char dummy[1024];

}Block;

typedef vector<Block> BlkVector;
void show_space(BlkVector * blk_vec)

{

cout<<
"size = "<< blk_vec->size() <<
", capacity = " << blk_vec->capacity() << endl;

}
int main(
int argc,
char *args[])

{

BlkVector bv;

Block b;

show_space(&bv);

bv.push_back(b);

show_space(&bv);
for(
int i = 0 ; i < 1000 ; i++)

{

bv.push_back(b);

}

show_space(&bv);
while( bv.size() > 0 )

{

bv.pop_back();

}

show_space(&bv);

BlkVector().swap(bv);

show_space(&bv);

}
| vector::swap |
public member function |
void swap ( vector<T,Allocator>& vec ); |
|
Swap content
Exchanges the content of the vector by the content of
vec, which is another vector of the same type. Sizes may differ.
After the call to this member function, the elements in this container are those which were in
vec before the call, and the elements of
vec are those which were in this. All iterators, references and pointers remain valid for the swapped vectors.
Notice that a global algorithm function exists with this same name,
swap, and the same behavior.