Deleting an object in a vector of pointers

Hello

I have a vector of pointers to objects of the Ball class. I am trying to delete the last one, but I'm not sure if I'm doing it correctly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 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
}





Is it correct?

Thank you

marc


It is correct, although I don't get why you need some mind-twisting loop just to delete the last element.
1
2
delete bola.back();
bola.pop_back();
would've been sufficient.

Using a vector to store pointers is very error-prone and violates RAII, though. You should use boost::ptr_vector instead.
Thanks Athar

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?

Thanks!

marc


If Ball is properly copyable, then that should not be a problem.
Topic archived. No new replies allowed.