Non-allocating Circular Buffer in C++

submited by
Style Pass
2024-11-15 21:00:03

A circular buffer or circular queue is a fixed capacity queue. If you add an element to the queue and the queue is at full capacity then it makes room by evicting the oldest item at the front of the queue. This way, the queue never runs of space.

Circular buffer is useful when you have limited space and don’t mind losing older information when new information becomes available. We can use this in a live video playback. Each frame received from the Internet is added to a fixed capacity queue. The player takes a frame from the front of the queue and renders it. If the player takes too long to finish rendering a frame then the queue may become full. Any new frame added will evict older frames. That is OK. The player will eventually catch up with the latest frames. This way we don’t introduce any delay from the latest live event.

In a video game we can put mouse movement coordinates in a circular queue. If the user moves the mouse too rapidly for the game to process the queue can become full. As new mouse coordinates are added to the queue the older values will get discarded.

Leave a Comment