From 8c146685206bae1218e57f2b798fca137367473b Mon Sep 17 00:00:00 2001 From: Jeremie Deray <jeremie.deray@pal-robotics.com> Date: Fri, 28 Oct 2016 17:07:03 +0200 Subject: [PATCH] add singleton.h --- src/singleton.h | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/singleton.h diff --git a/src/singleton.h b/src/singleton.h new file mode 100644 index 000000000..c632b5bba --- /dev/null +++ b/src/singleton.h @@ -0,0 +1,65 @@ +/** + * \file singleton.h + * + * Created on: Aug 31, 2016 + * \author: Jeremie Deray + */ + +#ifndef WOLF_SINGLETON_H_ +#define WOLF_SINGLETON_H_ + +#include <memory> + +namespace wolf { +namespace internal { + +/** + * \brief A thread-safer Singleton implementation with + * argument forwarding. + **/ +template <class T> +class Singleton +{ + /** + * \brief Custom deleter to by-pass private destructor issue. + **/ + struct Deleter; + + using SingletonOPtr = std::unique_ptr<T, Deleter>; + +public: + + template <typename... Args> + static T& get(Args&&... args) + { + static SingletonOPtr instance_(new T(args...)); + + return *instance_; + } + + constexpr Singleton(const Singleton&) = delete; + //constexpr Singleton(const Singleton&&) = delete; + + constexpr Singleton& operator=(const Singleton&) = delete; + //constexpr Singleton& operator=(const Singleton&&) = delete; + +protected: + + Singleton() = default; + + virtual ~Singleton() = default; +}; + +template <class T> +struct Singleton<T>::Deleter +{ + void operator()( const T* const p ) + { + delete p; + } +}; + +} // namespace internal +} // namespace wolf + +#endif /* WOLF_SINGLETON_H_ */ -- GitLab