我有以下代码使用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