[ACCEPTED]-Vector Iterators Casting-casting

Accepted answer
Score: 12
while (!myVector.empty())


  • You should probably use dynamic_cast instead of the hard cast. (If it's sure that there are only DerivedClass objects in the vector, why isn't it std::vector<DerivedClass>?)
  • You should probably not have to cast at all, since Shutdown() should be declared in the base class.
  • You should probably delete the objects, too, before you pop them off the vector. (But that might not be so.)
  • You should probably use a smart pointer which calls Shutdown() (and delete, probably).

Edit: Using std::vector<T>::clear(), as shown by markh44 is probably better than 1 the pop_back().

Score: 2

Could you make Shutdown a virtual function 5 in BaseClass? Then you wouldn't need a 4 cast.

Also you'll probably have trouble removing 3 items from a vector while iterating. I'd 2 do it like this:

vector<BaseClass*>::iterator iter;

for (iter = myVector.rbegin(); iter != myVector.rend(); iter++)

Edit: and another thing, ++iter 1 is generally preferred over iter++.

Score: 1

The constructor casting doesn't work for 2 pointers. Use static_cast if you're sure 1 or dynamic_cast and check.

More Related questions