加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 即使使用constexpr索引,编译器为什么允许超出范围的数组访

发布时间:2020-12-16 06:44:57 所属栏目:百科 来源:网络整理
导读:例如,如果我们有一个std ::数组,并使用constexpr实例化一个超出绑定的元素,编译器将不会报告错误: constexpr int EvaluateSpecialArrayIndex(int a){ return a * sizeof(int); }arrayint,5 arr;cout arr[98] endl; //compiles finecout arr[EvaluateSpecial
例如,如果我们有一个std ::数组,并使用constexpr实例化一个超出绑定的元素,编译器将不会报告错误:
constexpr int EvaluateSpecialArrayIndex(int a)
{ return a * sizeof(int); }

array<int,5> arr;

cout << arr[98] << endl; //compiles fine

cout << arr[EvaluateSpecialArrayIndex(4)] << endl; //the same as above

我们不能限制这个吗?

解决方法

为了确保在编译时对constexpr函数进行求值,必须强制它们使其结果为constexpr.例如:
#include <array>

int
main()
{
    constexpr std::array<int,5> arr{1,2,3,4,5};
    int i = arr[6];  // run time error
}

然而:

#include <array>

int
main()
{
    constexpr std::array<int,5};
    constexpr int i = arr[6];  // compile time error
}

不幸的是,为了实际工作,std :: array必须符合C14规范,而不是C 11规范.由于C 11规范没有使用constexpr标记std :: array :: operator []的const过载.

所以在C 11,你没有运气.在C 14中,您可以使其工作,但只有数组和调用索引运算符的结果都声明为constexpr.

澄清

数组索引的C 11规范如下:

reference operator[](size_type n);
          const_reference operator[](size_type n) const;

而数组索引的C14规范如下:

reference operator[](size_type n);
constexpr const_reference operator[](size_type n) const;

即constexpr被添加到C14的const过载.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读