使用此代码:
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;
}
我们有:
/tmp$ ./prorgam.out
Continuing on our merry way
We caught an int exception with value: -1
catch
怎么办块读取-1
如 int&
?我们无法为非常量左值引用赋值。为什么是第二个
std::cout
在第一个 std::cerr
之前执行的语句陈述?
最佳答案
这没关系,因为 [except.throw]/3
Throwing an exception copy-initializes ([dcl.init], [class.copy.ctor]) a temporary object, called the exception object. An lvalue denoting the temporary is used to initialize the variable declared in the matching handler ([except.handle]).
强调我的
如您所见,即使它是临时的,编译器也将其视为用于初始化处理程序的左值。因此,您不需要 const 引用。
关于c++ - throw 和捕捉整数是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59412118/