从throw表达式引发异常

Cur*_*ous 1 c++ exception language-lawyer c++17

在clang上运行以下代码会因分段错误而退出

#include <stdexcept>

int foo() {
    throw std::runtime_error{{}};
}

int main() {
    try {
        throw foo();
    } catch (...) {}
}
Run Code Online (Sandbox Code Playgroud)

https://wandbox.org/permlink/PrLRJyHq9o2K5Eez

但这在gcc https://wandbox.org/permlink/ORV2B5RfTl22RKxo上运行良好。阅读标准似乎没有明确表明这种事情是无效的。c在这里错了吗?

alt*_*gel 8

的构造函数std::runtime_error期望a std::stringconst char*。当您构造时std::runtime_error{{}},结果将nullptr作为传递const char*,这可能在std::runtime_error尝试复制字符串时导致UB 。

std::runtime_error用类似可构造的虚拟类型替换不会导致崩溃。

class X {
public:
    X(const std::string&){ std::cout << "const std::string&\n"; }
    X(const char*){ std::cout << "const char*\n"; }
};

int foo() {
    throw X{{}};
}

int main() {
    try {
        throw foo();
    } catch (...) {}
}
Run Code Online (Sandbox Code Playgroud)

现场例子

  • 最好解释一下为什么在这里选择`const char *`重载。 (3认同)