简体   繁体   中英

Cast an iterator of a vector of shared_ptr type

How can I cast an iterator of a vector of shared_ptr type? Consider following example:

typedef boost::shared_ptr < MyClass > type_myClass;

vector< type_myClass > vect;
vector< type_myClass >::iterator itr = vect.begin();

while(itr != vect.end())
{
   //Following statement works, but I wish to rather cast this 
   //to MyClass and then call a function?
   (*itr)->doSomething(); 
}

You do not want to cast , but rather extract a reference to the object:

MyClass & obj = *(*it); // dereference iterator, dereference pointer
obj.doSomething();

You can simply grab a reference by de-referencing it again.

MyClass& ref = **itr;

And then cast it or whatever however you'd like.

You can use the method get() , according to the docs :

T * get() const; // never throws
Returns: the stored pointer.

It means you can do:

type_myClass* ptr =  *itr.get();    
ptr->doSomething();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM