I should implement a logger for an application and I should use the singleton pattern. Moreover, since this application is multithreaded, this logger should be thread-safe. I would like to point out that I have to use C++03.
I've seen this implementation of singleton pattern in C++/QT using a QMutex
static object in order to guarantee that only one thread allocates the unique instance of the singleton object.
Why does everybody return a singleton as a pointer? I would return it as a reference, so I should not worry about explicitly free the memory used by the singleton object. I read this answer and this other answer and I wrote the following implementation.
// ==========
// Logger.h
#include <QMutex>
#include <QString>
class Logger
{
public:
static Logger& instance();
void configure(const QString& folder);
private:
Logger();
Logger(const Logger&);
Logger& operator=(const Logger&);
private:
mutable QMutex _mutex;
QString _folder;
};
// ==========
// Logger.cpp
Logger::Logger() : _mutex() { ; }
Logger& Logger::instance()
{
static QMutex mutex;
mutex.lock();
static Logger instance;
mutex.unlock();
return instance;
}
void Logger::configure(const QString& folder)
{
_mutex.lock();
_folder = folder;
_mutex.unlock();
}
I have some questions...
- Is the function
instance()
thread-safe when the unique instance is created? - At the time of the destruction of the object, will the singleton object destroyed in thread-safe manner?