- 论坛徽章:
- 0
|
本帖最后由 gta 于 2010-09-18 12:03 编辑
- #include <iostream>
- #include <map>
- #include <vector>
- using namespace std;
- class test
- {
- char s[1024];
- public:
- test()
- {cout<<"test() "<<this<<endl;
- }
- test(const test&)
- {cout<<"test(const test&) "<<this<<endl;}
- ~test()
- {cout<<"~test() "<<this<<endl;
- }
- };
- typedef std::map<int,test> testMap;
-
- void f()
- {
- testMap m_testMap;
- unsigned i=~0UL;
-
- while(i--);//用来拖时间,在这段时间内用top命令可以看到本程序的内存占用为0.4%
- //往map里灌20000个大对象
- for(int i = 0; i < 20000; i++)
- {
-
- m_testMap[i];
- }
-
- while(i--);//用来拖时间,在这段时间内用top命令可以看到本程序的内存占用升到8.4%
-
- for(int i =19999; i >=0 ; i--)
- {
- m_testMap.erase(i);
- }
- while(i--);//用来拖时间,在这段时间内用top命令可以看到本程序的内存占用降回0.4%
-
- }
-
-
-
- void g()
- {
- vector<test> v;
- test x;
- unsigned i=~0UL;
- while(i--);//用来拖时间,在这段时间内用top命令可以看到本程序的内存占用为0.4%
- cout<<"reserve"<<endl;
- v.reserve(20000);
- for(i=0;i<20000;i++)
- v.push_back(x);
- i=~0UL;
- while(i--);//用来拖时间,在这段时间内用top命令可以看到本程序的内存占用仍为0.4%,费解
-
- cout<<"clear"<<endl;
-
- v.clear();
- i=~0UL;
- while(1);
- }
-
-
- int main()
- {
- f();
-
- }
复制代码 如果在main中调 f(),这程序执行期间内存占用从不足1M涨到20多M,然后删除map容器中的对象后,又回落到不足1M,这是正常现象
但如果把main中的f()改成g(),把对象放到vector中,则程序在整个运行期间内存使用恒定,不足1M,但通过程序输出可以看到有20000个大对象被一次性创建,然后在clear时被一次性销毁,为什么内存占用恒定在一个很小的值上呢,请各位高人多多指教,谢谢 |
|