首页 > 解决方案 > 是否明确定义 C++ 将在编译时在文字类构造函数中进行数组边界检查?

问题描述

我发现在编译时运行下面的代码(clang 5.0/gcc7.1 with std=c++17),会报越界错误

int dummy[1];

struct CTest {
  constexpr CTest()  {
        dummy[100] = 1;
  }
};

constexpr CTest t;  // error: array subscript value ‘100’ is outside the bounds of array ‘dummy’ of type ‘int [1]’

但是在编译的时候运行一个正常的函数,是不会报错的。

constexpr int foo(int i)
{
    dummy[1000] = i;
    return i;
}
int a[foo(1)];    //force foo run at compile time, no compile error

我想知道这种行为是否定义明确,在文字类构造函数中它将检查边界。

标签: c++

解决方案


推荐阅读