【问题标题】:Trying to throw a range error if array index is out of bounds (C++)如果数组索引超出范围,则尝试抛出范围错误(C++)
【发布时间】:2021-06-26 22:20:48
【问题描述】:

如果我的函数正在访问的数组索引超出范围,我正在尝试让我的程序抛出 std::range_error。传入的类型是size_t,因为栈中的内存位置可能有符号也可能无符号。

这是我尝试过的:

MyClass::MyClass(){ // default constr
    size = 10;
    ptr = new int[size];
} 

int MyClass::at(size_t position) const
{
    try
    {
        return ptr[pos];
    }
    catch (const std::range_error&)
    {
        cout << "Range Error" << endl;
    }   
}

int main() {
    // Test exceptions
    MyClass a;
    throw_(a.at(0), range_error);
}

谁能帮助纠正我的函数,以便在索引超出范围时抛出range_error

【问题讨论】:

  • 您正在捕获一个异常,您应该检查有效性并改为抛出。
  • java stack-overflow 组就这样结束了 --->
  • 今天早些时候有人问过这个问题。这回答了你的问题了吗? stackoverflow.com/questions/66875237/…
  • 调用未定义的行为不是触发超出范围异常的方法。除了 std::range_error 不用于此目的之外(它旨在用于 value 错误,这会违反一些域限制的限制,例如标准库中仅有的两个地方实际上可以抛出这个:字符串转换),你的代码应该验证position是否在[0...size)范围内,如果检测到不在范围内,抛出一个std::out_of_range异常(这正是针对这种情况而设计的)。
  • 你能把你的班级改成使用std::vector吗?如果是这样,那么您可以简单地使用vector::at(),例如:MyClass::MyClass() : vec(10) {} int MyClass::at(size_t position) const { return vec.at(pos); }

标签: c++ arrays c++11 pointers exception


【解决方案1】:

您的班级应该始终知道数组的大小。你可以立即知道传递的值是否超出范围并直接抛出。

您的try 无法使用。 operator[]() 不会抛出。它作为一个简单的内存偏移。

你的函数应该看起来更像这样:

int MyClass::at(size_t position) const
{
  if (position >= this->m_size) throw std::out_of_range("Bad idx passed to at()");

  return ptr[position];
}

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2013-08-12
    相关资源
    最近更新 更多