【发布时间】:2020-04-12 04:36:50
【问题描述】:
使用此代码:
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 语句之前执行?
【问题讨论】:
-
你确定这是你得到的确切输出吗?
We caught an int exception with value: -1应该先打印出来。 -
@Scheff,对不起,你是对的,第一个输出重定向到
error stream而不是standard stream。 -
@FrançoisAndrieux 允许它的原因是存在不同的语义。通常,对于临时对象,您不知道会发生什么,因此决定只允许对临时对象进行 const 引用。除了例外,我们知道对象的生命周期,我们可能想要修改它并将它重新抛出到更高的上下文中。为了促进这一点,该标准允许绑定到非 const 左值引用。
-
@FrançoisAndrieux
throw创建一个副本(或移动)您传递给它的对象。引用绑定到该副本。副本是左值是有道理的。