Visual Studio和Clang不会抛出std :: bad_array_new_length

时间:2016-06-01 16:45:39

标签: c++ gcc visual-c++ clang language-lawyer

这是对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]{System.Drawing.Icon icon1= CreateDesktopShortCut.Properties.Resources.Treetog_I_Documents;
,{{2}},avoided the allocation}; // 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中没有错误(可能是因为this answer中提到的{{3}})。

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

1 个答案:

答案 0 :(得分:3)

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

$5.3.4/7 New [expr.new]

  

如果出现以下情况,则noptr-new-declarator中的表达式是错误的:

     

...

     

(7.4) - new-initializer是一个braced-init-list和number   提供初始值设定项的数组元素(包括   在字符串文字(2.13.5)中终止'\ 0'超过了数字   要初始化的元素。

     

...

     

带有错误表达式的new-expression不会调用   分配函数并通过抛出类型的异常来终止   这将匹配类型为std::bad_array_new_length的处理程序(15.3)   (18.6.2.2)。