Ring Buffer
Overview
The ring buffer is a fixed-size buffer that is regarded as if it were circular. When data is written to the buffer, it is stored in sequential order up to its size, after which new data will overwrite the oldest data in the buffer. ring_buffer
is a template class parameterized by the underlying element type, T
, and the type of storage used, which defaults to std::vector<T>
, although it is also possible to use fixed sized storage such as std::array
as long as the size is a powers of 2. For efficiency, the ring buffer storage will maintain a size that is the power of 2. The ring_buffer
is not resizable after construction.
Declaration
template <typename T, typename Storage = std::vector<T>>
class ring_buffer
{
public:
using value_type = T;
using storage_type = Storage;
explicit ring_buffer();
explicit ring_buffer(std::size_t size);
ring_buffer(ring_buffer const& rhs) = default;
ring_buffer(ring_buffer&& rhs) = default;
ring_buffer& operator=(ring_buffer const& rhs) = default;
ring_buffer& operator=(ring_buffer&& rhs) = default;
std::size_t size() const;
void push(T val);
T const& front() const;
T& front();
T const& back() const;
T& back();
T const& operator[](std::size_t index) const;
T& operator[](std::size_t index);
void clear();
void pop_front();
Storage& store();
const Storage& store() const;
};
Expressions
Notation
T
-
Element type, e.g.
float
. S
-
Storage type, e.g.
std::vector<T>
. rb_type
-
A
ring_buffer<T, S>
type. rb
,a
,b
-
Objects of type
ring_buffer<T, S>
. val
-
Object of type
T
. i
-
Object of type
std::size_t
. s
-
Object of type
std::size_t
. a [, b, c, d]
-
Required
a
, optionalb, c, d
.
Type Construction
Expression | Semantics |
---|---|
|
Instantiate a
|
Type Accessors
Expression | Semantics |
---|---|
|
Get the underlying element type. |
|
Get the underlying storage type. |
Constructors and Assignment
Expression | Semantics |
---|---|
|
Default construct a ring buffer. This constructor is only applicable when a fixed sized storage is specified. |
|
Construct a ring buffer with specified size, |
|
Copy construct from |
|
Assign |
C++ brace initialization may also be used. |
Mutators
Expression | Semantics |
---|---|
|
Push the latest element, overwriting the oldest element. |
|
Clear the ring buffer. |
|
Pop the latest element. This
operation will not destruct the
element, but will instead allow
the ring buffer to overwrite the
element on the next |
Accessors
Expression | Semantics | Return Type |
---|---|---|
|
Get the ring buffer’s size. |
|
|
Get the latest element. |
|
|
Get the oldest element. |
|
|
Get the element at index i. |
|
|
Get a reference to the storage. |
|
i < 0 || i > rb.size()-1 is undefined behavior.
|