C++:当我添加一条看似无关的代码行时,分段错误就会消失

1 c++ iterator initialization vector segmentation-fault

我正在使用指针向量和它在C++中附带的迭代器.我最初写它的方式会导致seg fnault,但是看似微不足道的变化,声明并初始化一个未使用的变量,seg故障消失了.有谁知道为什么?

这是代码错误的代码.成功执行的最后一行是第8行(通过printf语句找到)和第4行的uncommeting获取segfault:

1 Intersect RayTracer::closestShape(Ray r){
2    vector<Shape *>::iterator itStart = scene.getShapes().begin();
3    vector<Shape *>::iterator itEnd = scene.getShapes().end();
4    //vector<Shape *> sceneShapes = scene.getShapes();  This is the unused line that will cause the code to run successfully if I uncomment it.
5    Intersect closest = Intersect();
6    for(;itStart != itEnd; itStart++){
7       Intersect currentIntersect = (*itStart)->intersect(r);
8      if(currentIntersect.isHit()){
9          if(currentIntersect.getT() < closest.getT()){
10              closest = currentIntersect;
            }
        }
     }
     return closest;
}
Run Code Online (Sandbox Code Playgroud)

而这里的工作版本不再是段错误:

1 Intersect RayTracer::closestShape(Ray r){
2    vector<Shape *> sceneShapes = scene.getShapes();
3    vector<Shape *>::iterator itStart = sceneShapes.begin();
4    vector<Shape *>::iterator itEnd = sceneShapes.end();
5    Intersect closest = Intersect();
6    for(;itStart != itEnd; itStart++){
7       Intersect currentIntersect = (*itStart)->intersect(r);
8      if(currentIntersect.isHit()){
9          if(currentIntersect.getT() < closest.getT()){
10              closest = currentIntersect;
            }
        }
     }
     return closest;
}
Run Code Online (Sandbox Code Playgroud)

如果有人能够澄清为什么会发生这种情况,那将非常感谢!如果我可以添加任何内容来澄清我的问题,请告诉我.

Den*_*lin 7

vector<Shape *> sceneShapes = scene.getShapes();在堆栈上创建持久对象. itStartitEnd指向有效的记忆.在第一个示例中,迭代器指向无效的内存,因为它们指向来自调用的临时对象,scene.getShapes()该对象已被立即销毁并使迭代器无效.

取消注释你的//vector<Shape *> sceneShapes = scene.getShapes();行时,它会返回与临时相同的内存边界的向量,并且迭代器再次有效!但它不是百分之百的机会是相同的,你必须非常小心避免这些问题.