【问题标题】:C++ Iterating through a vector of smart pointersC ++迭代智能指针向量
【发布时间】:2012-08-14 20:58:14
【问题描述】:

我有一个具有此功能的类:

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); 

    }
}

编译器告诉我类 boost::shared_ptr 没有名为“RenderShape”的成员,我觉得这很奇怪,因为 PrimShapeBase 类当然具有该功能,但位于不同的头文件中。 这是什么原因?

【问题讨论】:

  • 您将迭代器的声明与其初始化分开的任何特殊原因?以后需要i吗?为什么不for (vector&lt;sp_PrimShapeBase&gt;::iterator i = LineVector.begin() 或者更好的for (auto it = LineVector.begin()

标签: c++ stl vector smart-pointers


【解决方案1】:

你不是说

(*i)->RenderShape(destination); 

?

i 是迭代器,*ishared_ptr(*i)::operator-&gt;() 是对象。

【讨论】:

  • 很奇怪,他有括号,所以看起来他要么打错了(但那会导致问题,不确定)......
  • 当然,让它溜走是多么可悲啊。取消对迭代器的引用。赞赏
  • 我找不到任何地方可以解释,为什么我们需要双重取消引用,而不是使用 -&gt;,它应该 IMO 重复直到它命中真正的指针对象(或者 shared_ptr 被认为是指针?)。你能解释一下吗?
  • @sukhmel std::iterator 有一个重载的operator-&gt;
  • 据我所知,它没有重载,尽管此运算符是为迭代器定义的。你的意思是,这种重复只出现在-&gt; 过载的地方?
【解决方案2】:

那是因为i 是一个迭代器。取消引用一次会给你智能指针,你需要双重取消引用它。

(**i).RenderShape(destination);

(*i)->RenderShape(destination); 

【讨论】:

  • 如果只有 dereference 是一个后缀运算符,那么我们可以写成i*-&gt;RenderShape(destination); :)
  • 或者像i-&gt;-&gt;RenderShape(destination);这样不敬虔的东西
  • 如何引入一些语法糖,例如i--&gt;RenderShape(destination);?箭头越长,取消引用的步骤越多? :)
  • 我在撰写评论时曾短暂考虑过这个想法,但这当然会以可怕的方式被滥用。 :O
  • @FredOverflow 当然除非是i---&gt;RenderShape(),在这种情况下它将取消引用前一个元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 2014-10-13
  • 2021-12-26
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
相关资源
最近更新 更多