[ACCEPTED]-Vector Iterators Casting-casting
Accepted answer
while (!myVector.empty())
{
((DerivedClass*)(myVector.back()))->Shutdown();
myVector.pop_back();
}
Notes:
- You should probably use
dynamic_cast
instead of the hard cast. (If it's sure that there are onlyDerivedClass
objects in the vector, why isn't itstd::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()
(anddelete
, probably).
Edit: Using std::vector<T>::clear()
, as shown by markh44 is probably better than 1 the pop_back()
.
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++)
{
(*iter)->Shutdown();
}
myVector.clear();
Edit: and another thing, ++iter 1 is generally preferred over iter++.
The constructor casting doesn't work for 2 pointers. Use static_cast if you're sure 1 or dynamic_cast and check.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.