gpt4 book ai didi

c++ - Visual Studio 和 Clang 不会抛出 std::bad_array_new_length

转载 作者:太空狗 更新时间:2023-10-29 21:15:30 30 4
gpt4 key购买 nike

这是对 prior question 的跟进.

在以下程序中 Visual Studio 2015 and Clang两者都不会抛出 std::bad_array_new_lengthgcc does .

#include <iostream>
#include <random>
#include <exception>
#include <new>

int main()
{
std::random_device rd;
std::uniform_int_distribution<int> dist(2,2);
try {

auto arr = new int[dist(rd)][4][2]{{{1}},{{2}},{{3}}}; // may write to unallocated memory

auto val1 = arr[0][0][0];
auto val2 = arr[1][0][0];
auto val3 = arr[2][0][0];
auto result = val1 + val2 + val3;
std::cout << result;
}
catch (std::exception const& e) {
std::cerr << e.what() << '\n';
}
return 0;
}

在 Visual Studio 中,程序崩溃时没有任何消息。在 Clang 中没有错误(可能是因为它是 avoided the allocation 中提到的 this answer )。

三个编译器,三个结果。这是未定义的行为还是 Visual Studio 中的错误?

最佳答案

GCC 是正确的,行为由标准定义。

$5.3.4/7 新 [expr.new]

The expression in a noptr-new-declarator is erroneous if:

...

(7.4) — the new-initializer is a braced-init-list and the number of array elements for which initializers are provided (including the terminating ’\0’ in a string literal (2.13.5)) exceeds the number of elements to initialize.

...

a new-expression with an erroneous expression does not call an allocation function and terminates by throwing an exception of a type that would match a handler (15.3) of type std::bad_array_new_length (18.6.2.2).

关于c++ - Visual Studio 和 Clang 不会抛出 std::bad_array_new_length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37574449/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com