我正在使用 C++ 中附带的指针向量和迭代器。我最初编写它的方式会导致段错误,但是通过看似微不足道的更改,声明和初始化一个未使用的变量,段错误就会消失。有谁知道为什么?
这是段错误的代码。成功执行的最后一行是第 8 行(通过 printf 语句找到)和取消注释的第 4 行摆脱了段错误:
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;
}
这是不再出现段错误的工作版本:
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;
}
如果有人可以澄清为什么会发生这种情况,那将不胜感激!如果我可以添加任何内容来澄清我的问题,请告诉我。