Skip to content
Snippets Groups Projects
Commit 9671a977 authored by Wuttke, Joachim's avatar Wuttke, Joachim
Browse files

Simplify ISingleton

Thread-safety is guaranteed in C++11.
No more need for a mutex lock.
parent 05e10a0e
No related branches found
No related tags found
No related merge requests found
......@@ -15,10 +15,6 @@
#ifndef BORNAGAIN_CORE_BASICS_ISINGLETON_H
#define BORNAGAIN_CORE_BASICS_ISINGLETON_H
#include <iostream>
#include <mutex>
#include <stdexcept>
//! Base class for singletons.
//! @ingroup tools_internal
......@@ -27,37 +23,19 @@ template <class T> class ISingleton
public:
static T& instance()
{
static std::mutex single_mutex;
std::unique_lock<std::mutex> single_lock(single_mutex);
if (!m_instance) {
if (m_destroyed)
// In BornAgain, an ISingleton is deleted when and only when the application
// terminates. Therefore there is no point in re-creating a deleted ISingleton.
// To be 110% sure, we explicitly forbid re-creation.
throw std::runtime_error("Invalid attempt to re-create a deleted ISingleton");
static T theInstance;
m_instance = &theInstance;
}
return *m_instance;
static T m_instance;
return m_instance;
}
protected:
ISingleton() {}
virtual ~ISingleton()
{
m_instance = nullptr;
m_destroyed = true;
}
ISingleton() = default;
~ISingleton() = default;
private:
ISingleton(const ISingleton&) = delete;
ISingleton& operator=(const ISingleton&) = delete;
static T* m_instance;
static bool m_destroyed; //!< to detect re-creation
ISingleton(ISingleton&&) = delete;
ISingleton& operator=(ISingleton&&) = delete;
};
// for templated classes, initializations go into the .h file:
template <class T> T* ISingleton<T>::m_instance = nullptr;
template <class T> bool ISingleton<T>::m_destroyed = false;
#endif // BORNAGAIN_CORE_BASICS_ISINGLETON_H
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment