Correctness and design
I will skip all points miscco
already raised and go directly to void write and int read.
- Your
writeoverwrites old values when the buffer is full. - Your
readreturns zero if the buffer is empty.
Although understandable, it should at least be documenteddocumented:
/// Describe the class, what is the purpose, what is important
template<class T, size_t N> // see std::array
class CircularBuffer {
...
/// Write values into the buffer, overwrite old values when the buffer is full
void write(const T& data) {
or maybe:
/// Write values into the buffer
///\return true if written, false if buffer was full
bool write(const T& data) {
You can also notice that I made it a template, just like std::array - both the type and the capacity are now template parameters. The standard way of passing arguments to methods like write is to use const T&, but it has some drawbacks, so, if it trully is for embedded systems, then simple T is an option as well (knowing you are going to use it with integers and such). But document it (and/or add other template parameters with some defaults).
Synchronization (Locking)
If you are going to use it with multiple threads (or main loop vs. interrupt) then some form of synchronization is indeed needed, because there are possible race-conditions otherwise, like one thread being inside write, just overwriting the oldest slot, while another thread can be inside read getting this newest element, while it should get the oldest, but tail was not yet updated by the first thread.
First question to ask is: How many threads / concurrent readers and writers (producers and consumers)?
Generic solution could use mutex but there can be better solutions for single producer single consumer (e.g. main loop vs. interrupt - USART and similar communication synchronization). One possibility is to use separate (atomic) write and read counters (like head and tail but you always only increase the counters and substract them to get number of elements inside the buffer - but be careful with order of operations, it is not trivial).