C++如何定义运算符[]来写入和读取循环缓冲区的一项

C++ how to define the operator [] to write and read an item of the circular buffer

我创建了一个实现循环缓冲区的模板 class。缓冲区由具有 T 类型值的项组成。

我想定义运算符[ ] 来写入和读取缓冲区的元素。即使当我尝试读取一个已经初始化的元素时,结果也是:Segmentation fault: 11

这是运算符[]的代码:

// read
const T& operator[](size_type index) const {
    assert(index < _size);
    item *curr = _buffer + index;
    return curr->value;
  }
  
  // read and write
  T &operator[](size_type index) {
    assert(index < _capacity);

    item *curr = _buffer + index;

    if (index < _size) {
      return curr->value;
    }
    else {
      _size++;
      return curr->value;
    }
  }

我如何在 main.cpp 中使用运算符 [ ] 的示例:

cbuffer<int> b(4);

  std::cout << "b: " << b << std::endl;
  std::cout << "capacity: " << b.capacity() << std::endl;
  assert(b.capacity() == 4);
  std::cout << "size: " << b.size() <<
                 std::endl;
  assert(b.size() == 0);

  b[0] = 1;
  b[1] = 3;

当我尝试在缓冲区中写入新项目时发生错误。

有什么方法可以定义有效的运算符[ ]?

我有点猜测,因为您没有提供足够的上下文(如果不查看 class 的其余部分,很难判断 class 的一小部分是否正确)。但是好像_buffer是一个链表。项目结构中的 next 指针泄露了它

typedef struct item {
    T value;
    item *next;
};

但是您的 operator[] 代码假定 _buffer 是一个数组,

item *curr = _buffer + index;

在指针上使用 + 假定指针指向连续的内存块,但因为您有一个链表,所以情况并非如此。

相反,您需要编写一个循环,循环遍历您的链接列表,直到找到正确的项目。像这样

item *curr = _buffer;
while (index > 0) {
    curr = curr->next;
    --index;
}
return curr->value;