singleton with std::call_once

master
Denes Matetelki 13 years ago
parent 44f5171b19
commit a03968e42e

@ -0,0 +1,41 @@
#ifndef SINGLETON_CALL_ONCE_HPP
#define SINGLETON_CALL_ONCE_HPP
#include <mutex>
template<typename T>
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<class T> T* Singleton_call_once<T>::m_instance = 0;
template<class T> std::once_flag Singleton_call_once<T>::m_flag;
#endif // SINGLETON_CALL_ONCE_HPP

@ -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

@ -0,0 +1,35 @@
#include <cxxtest/TestSuite.h>
#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<BasicSingleton>
{
public:
int getSeven()
{
TRACE;
return 7;
}
};
public:
void testBasic( void )
{
TEST_HEADER;
TS_ASSERT_EQUALS( BasicSingleton::getInstance()->getSeven(), 7 );
}
};
Loading…
Cancel
Save