C++ Iterating through a vector of smart pointers

2019-03-27 03:07发布

问题:

i have a class that has this function:

typedef boost::shared_ptr<PrimShapeBase> sp_PrimShapeBase; 



class Control{
     public:
         //other functions
         RenderVectors(SDL_Surface*destination, sp_PrimShapeBase);
     private:
         //other vars
          vector<sp_PrimShapeBase> LineVector;

};

//the problem of the program

void Control::RenderVectors(SDL_Surface*destination, sp_PrimShapeBase){
    vector<sp_PrimShapeBase>::iterator i;

    //iterate through the vector
    for(i = LineVector.begin(); i != LineVector.end(); i ++ ){
      //access a certain function of the class PrimShapeBase through the smart
      //pointers
      (i)->RenderShape(destination); 

    }
}

The compiler tells me that the class boost::shared_ptr has no member called 'RenderShape' which I find bizarre since the class PrimShapeBase certainly has that function but is in a different header file. What is the cause of this?

回答1:

Don't you mean

(*i)->RenderShape(destination); 

?

i is the iterator, *i is the shared_ptr, (*i)::operator->() is the object.



回答2:

That's because i is an iterator. Dereferencing it once gives you the smart pointer, you need to double dereference it.

(**i).RenderShape(destination);

or

(*i)->RenderShape(destination);