[pim/trojita] src/Common: Refactor FileLogger to use smartpointers
Espen Sandøy Hustad <[email protected]>
| Newsgroups | gmane.comp.kde.cvs |
|---|---|
| Message-ID | <[email protected]> |
Git commit f505961529c461c1dbf41da2170a8ceb3a36f427 by Espen Sandøy Hustad.
Committed on 03/08/2026 at 19:02.
Pushed by ehustad into branch 'master'.
Refactor FileLogger to use smartpointers
To simplify memory handling.
M +11 -20 src/Common/FileLogger.cpp
M +6 -4 src/Common/FileLogger.h
https://invent.kde.org/pim/trojita/-/commit/f505961529c461c1dbf41da2170a8ceb3a36f427
diff --git a/src/Common/FileLogger.cpp b/src/Common/FileLogger.cpp
index 9068c8069..5490f8742 100644
--- a/src/Common/FileLogger.cpp
+++ b/src/Common/FileLogger.cpp
@@ -23,39 +23,30 @@
#include <QDateTime>
#include <QDebug>
#include <QFile>
-#include <QTextStream>
#include "FileLogger.h"
namespace Common
{
FileLogger::FileLogger(QObject *parent) :
- QObject(parent), m_fileLog(nullptr), m_consoleLog(false), m_autoFlush(false)
+ QObject(parent), m_consoleLog(false), m_autoFlush(false)
{
}
void FileLogger::setFileLogging(const bool enabled, const QString &fileName)
{
- if (enabled) {
- if (m_fileLog)
- return;
-
- QFile *logFile = new QFile(fileName, this);
- logFile->open(QIODevice::Truncate | QIODevice::WriteOnly);
- m_fileLog = new QTextStream(logFile);
- } else {
- if (m_fileLog) {
- QIODevice *dev = m_fileLog->device();
- delete m_fileLog;
- delete dev;
- m_fileLog = nullptr;
- }
+ if (!enabled) {
+ m_fileLog.reset(nullptr);
+ return;
}
-}
-FileLogger::~FileLogger()
-{
- delete m_fileLog;
+ if (m_fileLog) {
+ return;
+ }
+
+ auto logFile = std::make_unique<QFile>(fileName, nullptr);
+ logFile->open(QIODevice::Truncate | QIODevice::WriteOnly);
+ m_fileLog = LogFilePtr(new QTextStream(logFile.release()));
}
void FileLogger::escapeCrLf(QString &s)
diff --git a/src/Common/FileLogger.h b/src/Common/FileLogger.h
index 47d4d5969..a44b21860 100644
--- a/src/Common/FileLogger.h
+++ b/src/Common/FileLogger.h
@@ -24,9 +24,11 @@
#define COMMON_FILELOGGER_H
#include <QObject>
-#include "Logging.h"
-class QTextStream;
+#include <QIODevice>
+#include <QTextStream>
+#include "Logging.h"
+#include <memory>
namespace Common
{
@@ -36,7 +38,6 @@ class FileLogger : public QObject
Q_OBJECT
public:
explicit FileLogger(QObject *parent = nullptr);
- ~FileLogger() override;
public slots:
/** @short A connection handler wants to log something */
@@ -53,7 +54,8 @@ private:
QString formatMessage(uint parser, const Common::LogMessage &message) const;
void escapeCrLf(QString &s);
- QTextStream *m_fileLog;
+ using LogFilePtr = std::unique_ptr<QTextStream, decltype([](QTextStream *stream) { stream->device()->deleteLater(); })>;
+ LogFilePtr m_fileLog;
bool m_consoleLog;
bool m_autoFlush;