2010-10-22 81 views
1

我在我的C++程序执行过程中出现错误(向量迭代器不兼容),我不明白。 [(在Windows/VISUAL C++ 2008速成)std ::向量迭代器不相容

这里是我的问题的一个简化版本:

#include <vector> 

class A 
{ 
    int mySuperInt; 
public: 
    A(int val) : mySuperInt(val) {} 
}; 
class B 
{ 
    std::vector<A*> myAs; 
    public: 
     B() 
     { 
      myAs.push_back(new A(1)); 
     }; 
     const std::vector<A*> getA() const {return myAs;} 
}; 

int main() 
{ 
    std::vector<B>* myBs = new std::vector<B>; 

    myBs->push_back(B()); 

    std::vector<B>::const_iterator it_B = myBs->begin(); 
    for (; it_B != myBs->end(); ++it_B) 
    { 
     std::vector<A*>::const_iterator it_A = it_B->getA().begin(); 
     for (; it_A != it_B->getA().end(); ++it_A) // <-- Error during execution: vector iterator incompatibles 
     { 
      // Do stuff 
      // ... 
     } 
    } 
} 

难道我错过了什么?

在此先感谢您的答案。

+0

你得到一个运行时错误?我只是编译这个并在Mac OS X上用gcc运行它。 – chrisaycock 2010-10-22 04:18:06

+0

那么你的问题是什么?你没有告诉我们你的问题是什么 - 难以回答... – 2010-10-22 04:26:47

+0

“我的C++程序执行过程中出现错误(向量迭代器不兼容),我不明白”不够清楚吗?真的吗? – 2010-10-22 15:38:01

回答

6

你的getA()函数按值返回一个向量。您将循环迭代器初始化为该向量的开头,但由于返回的向量是临时的,因此它在该行的末尾被销毁。

// at the end of this line the vector returned by getA is gone, so it_A is invalid. 
std::vector<A*>::const_iterator it_A = it_B->getA().begin(); 

因此迭代器不再有效。而应该返回一个参考这样的向量(注意&):

const std::vector<A*> & getA() const {return myAs;} 
+0

那是显而易见的。非常感谢JoshD! – 2010-10-22 13:02:24

1

你会意识到,B :: getAs()返回其多年期协定的副本。因此,it_A覆盖的向量与getA()。end()不断比较的向量不同。 for循环从不停止。 (更糟糕的是,它的范围超出了临时的向量<>,所以它被破坏,并且当你假装遍历它时,可以将各种随机废话写在该存储器上。)

1

感谢您的完整和简单的repro。这里的问题是你使用2个不同向量的迭代器,这是一个运行时调试检查。

您可能不打算这样做,但它是getA返回类型的结果。

您传回载体的拷贝和你的大概意思参考返回载体,就像这样:

const std::vector<A*>& getA() const {return myAs;}