发生错误后执行的代码

MrD*_*ive 2 c++ crash runtime-error

我用g ++版本4.8.2编译并运行以下C++代码:

vector<int> ivec{0,1,2};
int& iref = ivec[1];
for (int i=3;i<100;++i)
   ivec.push_back(i);
iref = 10;
cerr<<"After Error"<<'\n';
return 0;
Run Code Online (Sandbox Code Playgroud)

程序将按预期在行中崩溃iref = 10;,因为引用无效.但字符串"After Error"被打印出来了.为什么?

这个问题的答案对我来说很重要,因为大多数时候我使用coutcerr找到导致运行时错误的行.

Ker*_* SB 6

您的程序具有未定义的行为,因为push_back该引用无效iref.C++标准没有指定执行程序的任何行为.在C++的上下文中无法回答"为什么"这个问题.