【问题标题】:Must `throw nullptr` be caught as a pointer, regardless of pointer type?无论指针类型如何,都必须将“throw nullptr”作为指针捕获吗?
【发布时间】:2021-12-17 17:10:45
【问题描述】:

以下程序抛出nullptr,然后将异常捕获为int*

#include <iostream>

int main() {
    try {
        throw nullptr;
    }
    catch(int*) {
        std::cout << "caught int*";
    }
    catch(...) {
        std::cout << "caught other";
    }
}

在 Clang 和 GCC 中,程序成功打印 caught int*,演示:https://gcc.godbolt.org/z/789639qbb

但是在 Visual Studio 16.11.2 中,程序会打印出caught other。这是 MSVC 中的错误吗?

【问题讨论】:

  • 除了测试编译器是否符合 C++ 标准,为什么还有人想要throw nullptr;
  • @dan04 因为这很容易?与throw 0;throw "bug"; 相同。又快又脏。 (很脏。)
  • @dan04:因为我们可以!该语言提供了该功能,那么为什么不使用它呢?我也喜欢写volatile const unsigned const long unsigned int volatile long x = 5;,因为它会让下一个开发者反思 C++ 是否真的是正确的语言:-)

标签: c++ exception language-lawyer


【解决方案1】:

根据标准[except.handle],看起来像 Visual Studio 中的一个错误:

处理程序匹配E if 类型的异常对象

[...]

  • 处理程序的类型为cv Tconst T&amp;,其中Tpointerpointer-to-&gt;member 类型,Estd​::​nullptr_t

【讨论】:

  • 谢谢。我报告了 MSVC 错误:developercommunity.visualstudio.com/t/…
  • 对应 GCC bug report。这已在 GCC 7 中修复。
  • @alex_noname 感谢您的链接。这让我完全放松。每当 PM 或 PO 下次与我交谈时,我都会提及这个 bug,并告诉他们修复这个问题不会需要 2 周,而是 4 年。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 2023-03-27
  • 2023-03-28
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
相关资源
最近更新 更多