首页 > 解决方案 > 关于标准容器内边界检查的问题

问题描述

我编写了一个函数,该函数返回索引处的数据,用于简单实现类似于std::array.

constexpr const T& at(size_t index) const
{
  if(index < Size)
    return data_[index];
  throw std::out_of_range ("Index out of range");
}

Size模板参数在哪里。

我的问题是关于传递一个负索引让我们说:array.at(-1)

即使没有检查索引为负值的特定情况,这也会引发索引越界异常。为什么会自动处理?我很困惑。

标签: c++indexoutofboundsexceptionstdarray

解决方案


根据Adrian Mole 的评论 , size_t 类型是无符号的,因此您实际上不能通过 -1。它将被转换为 UINT_MAX (或类似的东西)。


推荐阅读