// Creation of the vector of pointers
std::vector<Ball *> bola;
// Addition of some pointers to objects
for (int i=0; i<10; i++) {
bola.push_back(new Ball());
}
// I perform some operations
for (int i=0; i<10 i++) {
bola[i]->draw();
}
int bola_length = bola.size(); // size of the vector
for(int i=bola_length;i>bola_length-1;i--){
delete bola[i-1]; // delete the object referenced by the pointer
bola.pop_back(); // shortening the vector (and deleting the pointer?)
cout << bola.size() << "\n"; // checking new size of the vector
}
The last loop is because I delete batches of 5 elements, but I simplified the example and forgot to remove the loop.
I also tried to create a vector of objects (instead of a vector of pointers to objects) but had problems when creating them in a loop. Example:
1 2 3 4 5 6 7 8
// Creation of the vector of objects
std::vector<Ball> bola;
for (int i=0; i<numballs; i++) {
Ball temp; // creation of a temporary Ball
bola.push_back(temp); // storing the temporary Ball in the vector
}
The problem here is that when "temp" is destroyed in every iteration, it's destructor is also called, which caused some trouble. Is there some way to avoid that?