Gha*_*ani 15 c++ exception try-catch
使用此代码:
int main()
{
try
{
throw -1;
}
catch (int& x)
{
std::cerr << "We caught an int exception with value: " << x << std::endl;
}
std::cout << "Continuing on our merry way." << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我们有:
/tmp$ ./prorgam.out
Continuing on our merry way
We caught an int exception with value: -1
Run Code Online (Sandbox Code Playgroud)
catch块如何读取-1为int&?我们无法为非常量左值引用赋值。
为什么第二条std::cout语句在第一条std::cerr语句之前执行?
Nat*_*ica 10
这是可以的,因为[except.throw]/3
抛出异常复制初始化([dcl.init],[class.copy.ctor])一个临时对象,称为异常对象。表示临时值的左值用于初始化在匹配处理程序([except.handle])中声明的变量。
强调我的
如您所见,即使它是临时的,编译器也将其视为用于初始化处理程序的左值。因此,您不需要 const 引用。