c++ - 为什么通过 int& 捕获 const int& 有效?

标签 c++ exception constants

在下面的代码中,我抛出一个 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&?

最佳答案

except.handle/3 :

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/

相关文章:

c++ - 将 long int 转换为 wxString

c++ - 将 Char* 分配给字符串变量后删除

c# - 在 C++/CLI 中处理 C# 异常

java - 如何避免 ResultSet 是 Java 中的关闭异常?

C++ 风格从 unsigned char * 转换为 const char *

c++ - 智能指针的迭代和容器

c++ - 如何修复 "Overloaded member function not found"错误?

javascript - 如何抛出 InvalidArgumentException JavaScript?

Mysql选择双常量

c++ - 在 C++ 中将指针变量分配给 const int?