使用自动时不检查数组范围

sch*_*tbi 10 c++ clang clang++

使用编译此代码-Warray-bounds。声明array2时收到警告array index 3 is past the end of the array (which contains 3 elements)。但是,在声明array1时,即使它必须是相同的类型,从而携带相同的大小信息,也并非如此。这是c中的错误吗?

enum class Format : int {
  Off = 55,
  FormatA = 66,
  FormatB = 77,
};

inline Format (&AllFormats())[3] {
  static Format values[] = {
    Format::Off,
    Format::FormatA,
    Format::FormatB
  };
  return values;
}

int main()
{
    auto array1 = AllFormats();    
    auto v3 = array1[3];

    Format (&array2)[3] = AllFormats();    
    v3 = array2[3];
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 7

即使它必须是相同的类型

您会认为的。但是,如果您检查一下,就会发现它们实际上不是同一类型:

std::cout << typeid(array1).name() << "\n";
std::cout << typeid(array2).name() << "\n";
Run Code Online (Sandbox Code Playgroud)
P6Format
A3_6Format
Run Code Online (Sandbox Code Playgroud)

哎呀。AllFormats当分配给auto变量时,由by返回的数组将衰减为指针,因为这是类型推导规则的auto工作方式。比较:

int& foo() {
    static int x = 42;
    return x;
}

auto x = foo(); // Type of `x` is `int`, not `int&`.
Run Code Online (Sandbox Code Playgroud)

为防止这种情况,请声明array1auto&auto&&

  • 这样的事情真的让我对C ++失去信心! (2认同)