经过数天的调试,我创建了一个非常简单的代码,但它也存在相同的问题。
#include <iostream>
#include <list>
// Object that occupies 128KB.
// Data is not important.
class MyObject
{
public:
int * a;
int * b;
int * c;
int * d;
MyObject( )
{
a = new int[ 8192 ];
b = new int[ 8192 ];
c = new int[ 8192 ];
d = new int[ 8192 ];
}
MyObject( const MyObject & m )
{
a = new int[ 8192 ];
b = new int[ 8192 ];
c = new int[ 8192 ];
d = new int[ 8192 ];
}
~MyObject( )
{
delete [] a;
delete [] b;
delete [] c;
delete [] d;
}
void operator=( const MyObject &m )
{
//Do nothing.
}
};
typedef std::list< MyObject > list_t;
#define MB_TO_ALLOC 1000 // Size in MB that the program must alloc.
#define SLEEP_TIME 5 // Time in seconds that the program must wait until go to another step.
// It's used to give sufficient time for tools update the memory usage
int main( )
{
std::cout << "Alloc..." << std::endl;
list_t * list = new list_t( );
// Number of objects for alloc MB_TO_ALLOC amount of memory
int nObjects = MB_TO_ALLOC * 1024 / 128;
for( int i = 0; i < nObjects; ++i )
list->push_back( MyObject( ) );
std::cout << SLEEP_TIME << "s to Dealloc..." << std::endl;
// Wait some time for a tool (like top) to update the memory usage
sleep( SLEEP_TIME );
std::cout << "Dealloc..." << std::endl;
delete list;
std::cout << SLEEP_TIME << "s to Alloc..." << std::endl;
// Wait some time for a tool (like top) to update the memory usage
sleep( SLEEP_TIME );
//Repeats the procedure for evaluating the reuse of memory
std::cout << "Alloc..." << std::endl;
list = new list_t( );
for( int i = 0; i < nObjects; ++i )
list->push_back( MyObject( ) );
std::cout << SLEEP_TIME << "s to Dealloc..." << std::endl;
sleep( SLEEP_TIME );
delete list;
}
我曾尝试使用简单的数组或自己编写的列表类,但是在这些情况下,内存会被正常释放。
有人知道发生了什么事吗?如何防止该内存被“保留”?
谢谢!
-- Bruno Caponi
boost::scoped_ptr
(它有一个非常简单的实现)。 - James McNellisMyObject
需要一个赋值运算符。否则你会两次删除相同的内存块。 - Derek Ledbetter