How it works...

We implement our ring buffer as a templated C++ class that has three private data fields:

  • objects: A static array of N elements of type T
  • read: An index to read elements from
  • write: An index to write elements to

The RingBuffer class exposes three public methods:

  • push(): To write data into the buffer
  • pull(): To read data from the buffer
  • has_data(): To check whether the buffer contains data

Let's take a close look at how they work.

The push() method is intended to be used by a function to store data in the buffer. Unlike the similar push() method for a dynamic queue or dynamic stack, which accepts a value to store as a parameter, our implementation does not accept any parameters. Since all elements are preallocated at compile ...

Get Embedded Programming with Modern C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.