Skip to content

Commit

Permalink
Make MessageQueue::pop return a unique_ptr
Browse files Browse the repository at this point in the history
Avoids accidental memory leaks
  • Loading branch information
Flamefire committed Jan 28, 2022
1 parent 423c6e3 commit d16fc41
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 20 deletions.
10 changes: 4 additions & 6 deletions libs/network/include/s25util/MessageQueue.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@

#pragma once

#include "Message.h"
#include "MessageHandler.h"
#include <boost/ptr_container/ptr_deque.hpp>
#include <cstddef>
#include <deque>
#include <memory>
#include <queue>

class Message;
class Socket;

// class Socket;
Expand Down Expand Up @@ -45,12 +46,9 @@ class MessageQueue : protected MessageHandler
/// hängt ein Element hinten an.
void push(Message* message);
/// liefert das vorderste Element der Queue.
Message* front();
Message* peek();
/// entfernt das vorderste Element aus der Queue.
void pop();
/// Returns the first element and removes it from the queue. Returns nullptr if there is none
/// Caller is responsible for deleting it!
Message* popFront();
std::unique_ptr<Message> pop();

private:
boost::ptr_deque<Message> messages;
Expand Down
19 changes: 5 additions & 14 deletions libs/network/src/MessageQueue.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,25 +25,16 @@ void MessageQueue::push(Message* message)
messages.push_back(message);
}

Message* MessageQueue::front()
Message* MessageQueue::peek()
{
return (!messages.empty() ? &messages.front() : nullptr);
return messages.empty() ? nullptr : &messages.front();
}

/**
* entfernt das vorderste Element aus der Queue.
*/
void MessageQueue::pop()
{
if(!messages.empty())
messages.pop_front();
}

Message* MessageQueue::popFront()
std::unique_ptr<Message> MessageQueue::pop()
{
if(messages.empty())
return nullptr;
return messages.pop_front().release();
return std::unique_ptr<Message>(messages.pop_front().release());
}

int MessageQueue::recv(Socket& sock, unsigned timeoutInMs)
Expand Down Expand Up @@ -98,7 +89,7 @@ bool MessageQueue::send(Socket& sock, int max, unsigned sizelimit)
int count = 0;
while(count <= max && !messages.empty())
{
const Message& msg = *front(); //-V522
const Message& msg = *peek(); //-V522

if(msg.getId() > 0)
{
Expand Down

0 comments on commit d16fc41

Please sign in to comment.