我有下面的代碼使用一個std ::列表容器來測試內存釋放:爲什麼編譯器推遲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
你是如何測量內存消耗的? – NPE