环形缓冲区是一种固定大小的FIFO数据结构,使用数组和读写索引实现高效存取,通过取模运算形成环形循环,配合full标志区分空满状态,适用于生产者-消费者等场景。

环形缓冲区(Ring Buffer),也叫循环队列,是一种固定大小的先进先出(FIFO)数据结构,常用于生产者-消费者场景、网络数据缓存等。C++ 中实现环形缓冲区可以使用数组和两个指针(或索引)来管理读写位置。
基本原理
环形缓冲区底层通常用一个固定大小的数组实现,配合两个索引:
- write_index(写索引):指向下一个可写入的位置
- read_index(读索引):指向下一个可读取的位置
当索引到达数组末尾时,通过取模运算回到开头,形成“环形”效果。
简单模板实现
下面是一个线程不安全但高效的基础环形缓冲区模板实现:
立即学习“C++免费学习笔记(深入)”;
templateclass RingBuffer { private: T buffer[Capacity]; size_t read_index = 0; size_t write_index = 0; bool full = false; public: bool push(const T& item) { if (full) return false; buffer[write_index] = item; write_index = (write_index + 1) % Capacity; // 写入后如果写索引追上读索引,表示满了 full = (write_index == read_index); return true; }
bool pop(T& item) { if (empty()) return false; item = buffer[read_index]; read_index = (read_index + 1) % Capacity; full = false; // 只要读了,就一定不满 return true; } bool empty() const { return (!full && (read_index == write_index)); } bool is_full() const { return full; } size_t size() const { if (full) return Capacity; if (write_index >= read_index) return write_index - read_index; else return Capacity - (read_index - write_index); }};
使用示例
你可以这样使用上面的 RingBuffer:
#includeint main() { RingBuffer
rb; rb.push(1); rb.push(2); rb.push(3); int val; while (rb.pop(val)) { std::cout zuojiankuohaophpcnzuojiankuohaophpcn val zuojiankuohaophpcnzuojiankuohaophpcn " "; } // 输出: 1 2 3 return 0;}
关键点说明
几个需要注意的地方:
- 满/空判断:读写索引相等时可能为空也可能为满,所以额外用一个 full 标志位区分
-
取模运算:容量为2的幂时可用位运算优化,如
write_index = (write_index + 1) & (Capacity - 1); - 线程安全:上述实现非线程安全。多线程环境下需加锁(如 std::mutex)或使用原子操作设计无锁队列
- 拷贝语义:默认生成的拷贝构造函数和赋值操作可行,但要注意语义是否符合预期
基本上就这些。这个实现简洁高效,适合嵌入式、音视频处理等对性能敏感的场景。根据需求可扩展为动态容量、支持移动语义、添加 front()/back() 接口等。










