Vector Iterators

Hi, In C ++, I have a vector like:

vector<BaseClass*> myVector;

In which I insert (push_back) pointers of derived classes into it.

Now I want to rotate my elements back so that I do this:

vector<ADlgcDev*>::iterator iter;

for (iter = myVector.rbegin(); iter != myVector.rend(); iter++)
{
 // but before I pop it, I need to shutdown it down
 // so I cast this
 // but this way, I'm unable to call the function
 (DerivedClass*(*iter))->Shutdown();

 myVector.pop_back();
}

but, as mentioned in the comments before I pop it up, I need to call its Shutdown () method , and the cast does not work properly. Any resolutions? or impossible?

+5
source share
4 answers
while (!myVector.empty())
{
  ((DerivedClass*)(myVector.back()))->Shutdown();
  myVector.pop_back();
}

Notes:

  • You should use dynamic_casthard casting instead. (If he is sure that there are only objects in the vector DerivedClass, why is it not std::vector<DerivedClass>?)
  • , , , Shutdown() .
  • , , . ( .)
  • , , Shutdown() ( delete, ).

: std::vector<T>::clear(), markh44, , , pop_back().

+13

Shutdown BaseClass? .

, , . :

vector<BaseClass*>::iterator iter;

for (iter = myVector.rbegin(); iter != myVector.rend(); iter++)
{
    (*iter)->Shutdown();
}
myVector.clear();

: : ++ iter iter ++.

+2

. static_cast, , dynamic_cast .

+1

If Shutdown () is a virtual method of the base class, that is, BaseClass :: ShutDown (), you must directly call iter-> ShutDown ();

Otherwise, if the method is not virtual, you should use dynamic_cast.

vector<ADlgcDev*>::iterator iter;

for (iter = myVector.rbegin(); iter != myVector.end(); iter++)
{
 DerivedClassA* a = dynamic_cast<DerivedClassA*>( *iter ) ;
 if ( a ) a->ShutDownA();
 else
 {
 DerivedClassB* b = dynamic_cast<DerivedClassB*>(*iter);
 if ( b ) b->ShutDownB();
 // ... repeat for every class in hierarchy that might be in the vector.
 }
 myVector.pop_back();
}

Anyway, you are probably leaking memory if ShutDown () doesn't remove the object from itself (which is usually bad), or you keep duplicate pointers and delete them elsewhere, which is another risky idea.

-1
source

All Articles