I am trying to implement a simple raw queue in C++. This is what I have come up with
#include <queue>
#include <cstdint>
#include <array>
#include <cstring>
class simple_queue
{
private:
static constexpr uint32_t max_msg_size = 4096;
using char_msg = std::array<char, max_msg_size>;
std::queue<char_msg> char_queue;
public:
simple_queue() = default;
~simple_queue() = default;
simple_queue(simple_queue&&) = default;
simple_queue& operator=(simple_queue&&) = default;
uint32_t write(const char* const buff, const uint32_t size) noexcept
{
const uint32_t size_to_copy = std::min(max_msg_size, size);
char_msg tmp_msg;
std::memcpy(&tmp_msg, buff, size_to_copy);
char_queue.push(std::move(tmp_msg));
return size_to_copy;
}
uint32_t read(char* const buff, const uint32_t size) noexcept
{
if (char_queue.empty())
{
return 0;
}
const uint32_t size_to_copy = std::min(max_msg_size, size);
std::memcpy(buff, &char_queue.front(), size_to_copy);
char_queue.pop();
return size_to_copy;
}
};
Note that I am trying to implement this queue just to store raw char buffers. As far as I understand making it a template does not make sense in this case.
I have played with it a bit and it seems to work as I expect.
- What can I change with this implementation?
- Does it make sense to use a custom allocator in here? I am allocating memory every time I write to the queue; how can I use a custom allocator to allocate some default chunk of memory when the queue is constructed?