Originally Posted by
afflictedd2
I basically followed this example:
And you couldn't do it this way?
Code:
#include <vector>
class Object
{
};
int main()
{
using namespace std;
vector<Object*> vpObject;
for (int i=0; i<5; i++)
{
vpObject.push_back(new Object);
}
// delete all pointers in the vector
for (vector<Object*>::iterator iter = vpObject.begin(), end = vpObject.end();
iter != end; ++iter)
{
delete *iter;
}
return 0;
}
Note that the code is not exception safe: if std::bad_alloc is thrown the objects already dynamically created would never be destroyed. On the other hand, the OS would probably do clean up, but this is just a toy program so we can accept that. Also, if you really want destruction to occur in reverse order of construction then we should write:
Code:
// delete all pointers in the vector
for (vector<Object*>::reverse_iterator iter = vpObject.rbegin(), end = vpObject.rend();
iter != end; ++iter)
{
delete *iter;
}