以下程序在一个循环中创建对象并将引用存储在向量中以供将来删除。
我看到了一个不寻常的行为,即使对象在第二次迭代中被删除,与对象创建相比,getrusage 提供了更高的常驻内存。
执行环境在 Linux Kernel 3.2.0-49-generic 中。
#include <iostream>
#include <vector>
#include <stdio.h>
#include <mcheck.h>
#include <sys/time.h>
#include <sys/resource.h>
using namespace std;
void printUsage(string tag)
{
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
printf("%s -- Max RSS - %ld\n", tag.c_str() ,usage.ru_maxrss);
}
class MyObject
{
public:
char array[1024 * 1024];
MyObject() {};
~MyObject() {};
};
int main()
{
printUsage("Starting");
vector<MyObject *> *v = new vector<MyObject *>();
for(int i = 0; i < 10000; i++)
{
MyObject * h = new MyObject();
v->push_back(h);
// The max resident value is same. usual behavior.
// delete h;
}
printUsage("After Object creation");
for(size_t i = 0; i < v->size(); i++)
{
MyObject * h = v->at(i);
delete h;
}
v->clear();
delete v;
printUsage("After Object deletion");
return 0;
}
g++ test/test.cpp -Wall -O2 -g
输出
Starting -- Max RSS - 3060
After Object creation -- Max RSS - 41192
**After Object deletion -- Max RSS - 41380**