【发布时间】:2011-11-08 12:00:24
【问题描述】:
我有以下代码使用 std::list 容器测试内存释放:
#include <iostream>
#include <list>
#include <string>
#include <boost/bind.hpp>
/* count of element to put into container
*/
static const unsigned long SIZE = 50000000;
/* element use for test
*/
class Element
{
public:
Element()
: mId(0)
{}
Element( long id )
: mId(id)
{}
virtual ~Element()
{
}
inline long getId() const
{
return this->mId;
}
inline bool operator<( const Element & rightOperand ) const
{
return this->mId < rightOperand.mId;
}
inline bool isEven() const
{
return 0 == ( this->mId & 1 );
}
private:
long mId;
};
typedef std::list< Element > Elements;
int main( int argc, char * argv[] )
{
std::string dummy;
{
Elements elements;
std::cout << "Inserting "<< SIZE << " elements in container" << std::endl;
std::cout << "Please wait..." << std::endl;
/* inserting elements
*/
for( long i=0; i<SIZE; ++i )
{
elements.push_back( i );
}
std::cout << "Size is " << elements.size() << std::endl;
std::getline( std::cin, dummy); // waiting user press enter
/* remove even elements
*/
elements.remove_if( boost::bind( & Element::isEven, _1 ) );
std::cout << "Size is " << elements.size() << std::endl;
std::getline( std::cin, dummy);
}
std::getline( std::cin, dummy);
return 0;
}
运行此代码会得到以下内存配置文件:
看起来 gcc 正在推迟释放,在我的测试程序中,最后它别无选择,在返回命令行之前释放内存。
为什么释放这么晚?
我已经尝试使用向量来测试另一个容器,并且缩小以适应的技巧起作用并在我期望的时候释放释放的内存。
gcc 4.5.0, linux 2.6.34
【问题讨论】:
-
你是如何测量内存消耗的?
标签: c++ stl memory-management dealloc