FixedSizeQueue: modernize (std::array, std::move)
This commit is contained in:
parent
afa202738e
commit
9081d029e3
|
@ -4,33 +4,19 @@
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <array>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
// STL-look-a-like interface, but name is mixed case to distinguish it clearly from the
|
// STL-look-a-like interface, but name is mixed case to distinguish it clearly from the
|
||||||
// real STL classes.
|
// real STL classes.
|
||||||
|
//
|
||||||
// Not fully featured, no safety checking yet. Add features as needed.
|
// Not fully featured, no safety checking yet. Add features as needed.
|
||||||
|
|
||||||
// TODO: "inline" storage?
|
|
||||||
|
|
||||||
template <class T, int N>
|
template <class T, int N>
|
||||||
class FixedSizeQueue
|
class FixedSizeQueue
|
||||||
{
|
{
|
||||||
T* storage;
|
|
||||||
int head;
|
|
||||||
int tail;
|
|
||||||
int count; // sacrifice 4 bytes for a simpler implementation. may optimize away in the future.
|
|
||||||
|
|
||||||
// Make copy constructor private for now.
|
|
||||||
FixedSizeQueue(FixedSizeQueue& other) {}
|
|
||||||
public:
|
public:
|
||||||
FixedSizeQueue()
|
|
||||||
{
|
|
||||||
storage = new T[N];
|
|
||||||
clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
~FixedSizeQueue() { delete[] storage; }
|
|
||||||
void clear()
|
void clear()
|
||||||
{
|
{
|
||||||
head = 0;
|
head = 0;
|
||||||
|
@ -40,7 +26,7 @@ public:
|
||||||
|
|
||||||
void push(T t)
|
void push(T t)
|
||||||
{
|
{
|
||||||
storage[tail] = t;
|
storage[tail] = std::move(t);
|
||||||
tail++;
|
tail++;
|
||||||
if (tail == N)
|
if (tail == N)
|
||||||
tail = 0;
|
tail = 0;
|
||||||
|
@ -57,12 +43,18 @@ public:
|
||||||
|
|
||||||
T pop_front()
|
T pop_front()
|
||||||
{
|
{
|
||||||
const T& temp = storage[head];
|
T& temp = storage[head];
|
||||||
pop();
|
pop();
|
||||||
return temp;
|
return std::move(temp);
|
||||||
}
|
}
|
||||||
|
|
||||||
T& front() { return storage[head]; }
|
T& front() { return storage[head]; }
|
||||||
const T& front() const { return storage[head]; }
|
const T& front() const { return storage[head]; }
|
||||||
size_t size() const { return count; }
|
size_t size() const { return count; }
|
||||||
|
private:
|
||||||
|
std::array<T, N> storage;
|
||||||
|
int head = 0;
|
||||||
|
int tail = 0;
|
||||||
|
// Sacrifice 4 bytes for a simpler implementation. may optimize away in the future.
|
||||||
|
int count = 0;
|
||||||
};
|
};
|
||||||
|
|
Loading…
Reference in New Issue