在下面的代码中,我抛出一个 int,将其作为 const int& 捕获,重新抛出并再次捕获它,将其作为 int& 捕获。
#include <iostream>
int main()
{
try
{
try
{
int x = 1;
throw x;
}
catch(const int& e)
{
std::cout << "Inner catch" << std::endl;
throw;
}
}
catch(int & e1)
{
std::cout << "Outer catch" << std::endl;
}
return 0;
}
以上程序编译成功并打印
Inner catch
Outer catch
另一方面,我试图通过 const int& 初始化 int& 的以下程序甚至无法编译。
#include <iostream>
int main()
{
int x = 0;
const int& y = x;
int& z = y
return 0;
}
我得到了预期的以下错误
binding ‘const int’ to reference of type ‘int&’ discards qualifiers
int& z = y
为什么我可以将 const int& 捕获为 int& 但不能将 const int& 分配给 int&?
最佳答案
A handler is a match for an exception object of type E if
(3.1) – The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or [...]
关于c++ - 为什么通过 int& 捕获 const int& 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54301966/