From 5f8bec8d86a50768f6a8c371235de81a7529a3e5 Mon Sep 17 00:00:00 2001 From: f4exb Date: Sat, 8 Aug 2015 22:09:48 +0200 Subject: [PATCH] Added thread safe singleton class --- include/util/threadsafesingleton.h | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 include/util/threadsafesingleton.h diff --git a/include/util/threadsafesingleton.h b/include/util/threadsafesingleton.h new file mode 100644 index 000000000..349c00d37 --- /dev/null +++ b/include/util/threadsafesingleton.h @@ -0,0 +1,39 @@ +/* + * threadsafesingleton.h + * + * Created on: Aug 7, 2015 + * Author: f4exb + */ + +#ifndef INCLUDE_UTIL_THREADSAFESINGLETON_H_ +#define INCLUDE_UTIL_THREADSAFESINGLETON_H_ + +//! Template class used to make from a class a singleton. +/** S is the type of the singleton object to instantiate. +
This class permits to gather all singleton code in the same place + and not to pollute object interface with singleton methods. +
Accessing to the instance of S is made through ThreadSafeSingleton::instance() +
Note : The class using this adapter should have constructor and + destructor protected and copy constructor and operator= private. +
Besides it should declare the class ThreadSafeSingleton friend in order + this class can make the construction. +*/ + +template class ThreadSafeSingleton +{ +public: + static S& instance() { return *_pInstance; } + +protected: + ThreadSafeSingleton() {} + ~ThreadSafeSingleton() { delete _pInstance; } + static S* _pInstance; + +private: + ThreadSafeSingleton(const ThreadSafeSingleton&) {} + ThreadSafeSingleton& operator = (const ThreadSafeSingleton&) {return *this;} +}; + +template S *ThreadSafeSingleton::_pInstance = new S; + +#endif /* INCLUDE_UTIL_THREADSAFESINGLETON_H_ */