From a03968e42e26f931d37128e1829abcfb0f81b94f Mon Sep 17 00:00:00 2001 From: Denes Matetelki Date: Mon, 10 Oct 2011 10:32:19 +0200 Subject: [PATCH] singleton with std::call_once --- include/Singleton_call_once.hpp | 41 +++++++++++++++++++++++++++++++ test/CMakeLists.txt | 2 +- test/test_Singelton_call_once.hpp | 35 ++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 include/Singleton_call_once.hpp create mode 100644 test/test_Singelton_call_once.hpp diff --git a/include/Singleton_call_once.hpp b/include/Singleton_call_once.hpp new file mode 100644 index 0000000..117a913 --- /dev/null +++ b/include/Singleton_call_once.hpp @@ -0,0 +1,41 @@ +#ifndef SINGLETON_CALL_ONCE_HPP +#define SINGLETON_CALL_ONCE_HPP + +#include + +template +class Singleton_call_once +{ +protected: + + Singleton_call_once() {}; + virtual ~Singleton_call_once() {}; + +private: + + Singleton_call_once( const Singleton_call_once& ); + Singleton_call_once& operator=( const Singleton_call_once& ); + +public: + + static T* getInstance() + { + std::call_once(m_flag, &Singleton_call_once::do_init); + return m_instance; + } + +private: + + static void do_init() + { + m_instance = new T(); + } + + static T* m_instance; + static std::once_flag m_flag; +}; + +template T* Singleton_call_once::m_instance = 0; +template std::once_flag Singleton_call_once::m_flag; + +#endif // SINGLETON_CALL_ONCE_HPP diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 297a3f7..541227c 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -16,7 +16,7 @@ if(CXXTEST_FOUND) generated_main.cpp Fixture.hpp - test_Multiton.hpp + test_Singelton_call_once.hpp # test_Singleton.hpp # test_Singleton_meyers.hpp # test_Singleton_DCLP.hpp diff --git a/test/test_Singelton_call_once.hpp b/test/test_Singelton_call_once.hpp new file mode 100644 index 0000000..873530a --- /dev/null +++ b/test/test_Singelton_call_once.hpp @@ -0,0 +1,35 @@ +#include + +#define private public // need to reach Singleton's private m_instance + +#include "Common.hpp" +#include "Fixture.hpp" +#include "Singleton_call_once.hpp" + + +class TestSingletonCallOnceSuite : public CxxTest::TestSuite +{ + +private: + + class BasicSingleton : public Singleton_call_once + { + public: + int getSeven() + { + TRACE; + return 7; + } + }; + +public: + + void testBasic( void ) + { + TEST_HEADER; + + TS_ASSERT_EQUALS( BasicSingleton::getInstance()->getSeven(), 7 ); + } + + +};