, Modern C++, :
#ifndef SINGLETON_H
#define SINGLETON_H
template <typename C, typename ...Args>
class singleton
{
private:
singleton() = default;
static C* m_instance;
public:
~singleton()
{
delete m_instance;
m_instance = nullptr;
}
static C& instance(Args...args)
{
if (m_instance == nullptr)
m_instance = new C(args...);
return *m_instance;
}
};
template <typename C, typename ...Args>
C* singleton<C, Args...>::m_instance = nullptr;
#endif
:
int &i = singleton<int, int>::instance(1);
UTEST_CHECK(i == 1);
tester1& t1 = singleton<tester1, int>::instance(1);
UTEST_CHECK(t1.result() == 1);
tester2& t2 = singleton<tester2, int, int>::instance(1, 2);
UTEST_CHECK(t2.result() == 3);
The problem is that instance () requires arguments on every call, but uses them only on the first call (as noted above). The default arguments cannot be used at all. It might be better to use the create (Args ...) method, which should precede the call to instance () or throw an exception.
source
share