首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何实现对std::数组的绑定检查?

如何实现对std::数组的绑定检查?
EN

Stack Overflow用户
提问于 2018-03-22 01:27:37
回答 4查看 1.7K关注 0票数 1

我已经扩展了C++ 11 std::array,它是工作文件,但是当我试图重载operator[]时,我得到了以下错误:

代码语言:javascript
运行
复制
 error: lvalue required as left operand of assignment
 array[0] = 911;
              ^~~

是否可以为operator[]类型实现std::array添加绑定检查?

这是代码:

代码语言:javascript
运行
复制
#include <array>
#include <cassert>
#include <iostream>

template <unsigned int array_size, typename array_datatype=long int>
struct Array : public std::array<array_datatype, array_size>
{
  Array()
  {
  }

  // std::array constructor inheritance
  // https://stackoverflow.com/questions/24280521/stdarray-constructor-inheritance
  Array(std::initializer_list< array_datatype > new_values)
  {
    unsigned int data_size = new_values.size();
    unsigned int column_index = 0;
    // std::cout << data_size << std::endl;

    if( data_size == 1 )
    {
      this->clear(*(new_values.begin()));
    }
    else
    {
      assert(data_size == array_size);

      for( auto column : new_values )
      {
        (*this)[column_index] = column;
        column_index++;
      }
    }
  }

  array_datatype operator[](unsigned int line)
  {
    assert(line < array_size);
    assert(line > -1);
    return (*this)[line];
  }

  /**
   * Prints a more beauty version of the array when called on `std::cout<< array << std::end;`
   */
  friend std::ostream& operator<<( std::ostream &output, const Array &array )
  {
    unsigned int column;
    output << "{";

    for( column=0; column < array_size; column++ )
    {
      output << array[column];

      if( column != array_size-1 )
      {
        output << ", ";
      }
    }

    output << "}";
    return output;
  }
}

相关信息:

  1. 是否可以在g++中启用数组边界检查?
  2. 访问超出界限的数组不会产生错误,为什么?
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-03-22 02:08:22

如果要在赋值的左侧使用operator[]的返回值,则必须通过引用而不是按值返回数组元素。

您还具有一个递归循环,因为您正在从自身内部调用自己的operator[]。您希望调用基类的operator[],因此需要对其进行限定。

试试这个:

代码语言:javascript
运行
复制
array_datatype& operator[](unsigned int line)
{
    assert(line < array_size);
    assert(line > -1);
    return std::array<array_datatype, array_size>::operator[](line);
}
票数 4
EN

Stack Overflow用户

发布于 2018-03-22 01:30:33

您可以使用:

代码语言:javascript
运行
复制
array_datatype& operator[](unsigned int line)&
array_datatype const& operator[](unsigned int line)const&
array_datatype operator[](unsigned int line)&&
票数 2
EN

Stack Overflow用户

发布于 2018-03-24 19:10:30

如果希望绑定检查对数组元素的访问,只需使用std::vector (或std::array)的std::vector方法(或std::array),而不是[]运算符。为了这个目的,不要重新发明轮子:)。

有关数组边界检查的文档,请参见参考文献

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49419089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档