Daily Unreal Column #68 - TCircularBuffer
Sometimes you want to store fixed amount of elements in a container. On top of that, once you reach the limit, you want the newest element to replace the old one. That's what TCircularBuffer is for.
TCircularBuffer doesn’t have a default constructor and requires you to declare its size the moment its being created.
TCircularBuffer<float> Foo(1024);It also only has three functions available:
Capacity— returns the number of elements this buffer can storeGetNextIndex— calculates the next index that follows the given index as parameter to this functionGetPreviousIndex— calculates the previous index to the given index as parameter to this function
Let’s take a look at an example usage.
TCircularBuffer<float> Foo(1024);
for (int32 Index = 0; Index < 10000; Index++)
{
Foo[Index] = FMath::FRand();
}Notice that Index variable far exceeds the range of 0-1023 but this is fine. This is exactly what circular buffer is great at. Internally it uses a mask that allows us to pass any Index and it will apply the mask to it, effectively clamping it to the expected range of 0-1023.

