From d16fc41abfedb32ac9589bd41bb2436464a2aff5 Mon Sep 17 00:00:00 2001 From: Alexander Grund Date: Fri, 28 Jan 2022 14:55:26 +0100 Subject: [PATCH] Make MessageQueue::pop return a unique_ptr Avoids accidental memory leaks --- libs/network/include/s25util/MessageQueue.h | 10 ++++------ libs/network/src/MessageQueue.cpp | 19 +++++-------------- 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/libs/network/include/s25util/MessageQueue.h b/libs/network/include/s25util/MessageQueue.h index 9772f87..522d4f3 100644 --- a/libs/network/include/s25util/MessageQueue.h +++ b/libs/network/include/s25util/MessageQueue.h @@ -4,13 +4,14 @@ #pragma once +#include "Message.h" #include "MessageHandler.h" #include #include #include +#include #include -class Message; class Socket; // class Socket; @@ -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 pop(); private: boost::ptr_deque messages; diff --git a/libs/network/src/MessageQueue.cpp b/libs/network/src/MessageQueue.cpp index e65daeb..2ab172e 100644 --- a/libs/network/src/MessageQueue.cpp +++ b/libs/network/src/MessageQueue.cpp @@ -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 MessageQueue::pop() { if(messages.empty()) return nullptr; - return messages.pop_front().release(); + return std::unique_ptr(messages.pop_front().release()); } int MessageQueue::recv(Socket& sock, unsigned timeoutInMs) @@ -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) {