#include <iostream>
#include <vector>
using std::vector;
using std::cin;
using std::cout;
using std::endl;
vector < int * > Vec;
void Init( constint Count )
{
for( int i( 0 ); i < Count; i++ )
{
Vec.push_back( NULL );
if( ( Vec.at( i ) = newint( 0 ) ) == NULL )
break;
}
}
int main( )
{
Init( 2 );
for( unsignedint i( 0 ); i < Vec.size( ); i++ )
{
if( Vec.at( i ) )
{
delete Vec.at( i );
Vec.at( i ) = NULL;
Vec.erase( Vec.begin( ) );
}
else
Vec.erase( Vec.begin( ) );
}
cin.get( );
return 0;
}
When running this code, the last element of vec is never released. I've got a suspicion that it's Vec.erase( Vec.begin( ) ) on line 32. Can any find what I've done wrong?
This doesn't seem to make much sense. You delete the i'th element and then erase the first? Why?
Moreover, you're skipping the new i'th element after each erase, since you erased the first element (thus changing the indexes of all other elements) but aren't accommodating for this.
Other things: new cannot return NULL, so the check in line 16 has no effect.
Nor do you have to check a pointer for NULL when you delete it.
That gets us to:
1 2
for (uint i=0;i<vec.size();i++)delete vec[i];
vec.clear();
C++0x ways:
1 2
for (auto it=vec.begin();it!=vec.end();++it)delete *it;
for (int* p : vec)delete p;
1) no need to set it to NULL if you're going to be popping it right away
2) no need to check for NULL before deleting. The delete operator already does that (it's OK to delete a null pointer -- delete will just do nothing if that happens.