[英]C++ how to define the operator [] to write and read an item of the circular buffer
I have created a template class that implement a circular buffer.我创建了一个实现循环缓冲区的模板类。 The buffer is formed of items that have a value of type T.
缓冲区由具有类型 T 值的项目组成。
I want to define the operator[ ] to write and read an element of the buffer.我想定义 operator[] 来写入和读取缓冲区的元素。 Even when I try to read an element already inizialized the result is: Segmentation fault: 11
即使我尝试读取已经初始化的元素,结果也是:分段错误:11
This is the code for operator[ ]:这是操作符[]的代码:
// 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;
}
}
An example of how I use operator[ ] in main.cpp:我如何在 main.cpp 中使用 operator[] 的示例:
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;
The error occurs when I try to write a new item in the buffer.当我尝试在缓冲区中写入新项目时发生错误。
What could be a way to define the operator[ ] that works?有什么方法可以定义有效的运算符 []?
I'm guessing somewhat, because you haven't provided enough context (it's difficult to see if a small part of a class is correct without seeing the rest of the class).我有点猜测,因为您没有提供足够的上下文(很难在没有看到课程其余部分的情况下查看课程的一小部分是否正确)。 But it seems that
_buffer
is a linked list.但似乎
_buffer
是一个链表。 The next
pointer in the item struct gives it away项目结构中的
next
指针给出了它
typedef struct item {
T value;
item *next;
};
But your operator[]
code assumes that _buffer
is an array,但是您的
operator[]
代码假定_buffer
是一个数组,
item *curr = _buffer + index;
Using +
on a pointer assumes that the pointer is pointing at a contiguous block of memory but because you have a linked list that's not the case for you.在指针上使用
+
假定指针指向一个连续的内存块,但因为您有一个链表,这对您来说并非如此。
Instead you need to write a loop, that loops through your linked list until you find the correct item.相反,您需要编写一个循环,循环遍历您的链表,直到找到正确的项目。 Something like this
像这样的东西
item *curr = _buffer;
while (index > 0) {
curr = curr->next;
--index;
}
return curr->value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.