结束迭代器和分段错误

cod*_*ack 1 c++ unix iterator segmentation-fault

如果我们采用这个例子:

std::map<int,foo*> intmap;
fillMap(intmap);

// I will force this to end(), in real life this could be a "find" output
std::map<int,foo*>::iterator iter = intmap.end(); 
if(iter->second != 0)
    iter->second->whatever();
Run Code Online (Sandbox Code Playgroud)

我有分段错误(这是预期的,例子不是故意在"whatever()"调用上检查"iter!= intmap.end()"而不是" - >第二个"空指针检查:这是预期的行为吗?这个seg会在"whatever()"调用上系统地出错,还是依赖于特定的运行时内存条件?

提前感谢您的意见.贾科莫

Ros*_*ost 6

end()STL容器的解除引用和过去的迭代器是Undefined Behavior.没有什么可以称之为预期的.一切都可以发生,甚至可以发挥作用.它可能取决于很多因素,如编译器/库/操作系统版本,运行时环境状态,调试/发布版本等.所以你永远不应该假设如果你做脏禁止的事情会发生什么.