I am trying to implement a base class singleton using CRTP in a single threaded environnement where the instance is not held by the user, code is below:
#include <type_traits>
#include <atomic>
#include <cassert>
//Single threaded singleton.
//T is default constructable.
template<typename T>
class singleton
{
static bool m_empty;
public:
virtual ~singleton()
{
this->reset();
}
//YOU will end up with nullptr if I reset: YES THAT IS WHAT I WANT, YOU SHOULDN'T HAVE THE POINTER AT FIRST PLACE.
//Calls should be done this way: singleton::instance()->do_stuff(); Never hold the instance ++ Single threaded.
static T* instance()
{
static T* pme = new T();
if (pme)
return pme;
m_empty = false;
pme = new T();
return pme;
};
static bool reset()
{
if(m_empty)
return false;
T* pme = instance();
m_empty = true;
delete pme;
return true;
};
protected:
singleton() = default;
};
I can use the class as fellow:
class derive : public singleton<derive>
{
public:
derive() = default;
double get() const
{
return m_example;
}
private:
double m_example;
};
Q1. Is this ok please? (Please see the restriction above. I know this doesn't work in multithreaded environnement and if the instance is held).
Q2. I get error when doing this:
int main(int argc, char* argv[])
{
const double d = derive::instance()->get();
};
>main.cpp
1>main.obj : error LNK2001: unresolved external symbol "private: static bool singleton<class derive>::m_empty" (?m_empty@?$singleton@0_NA)
1>..\build\bin\Debug\windows\x86_64\tests\tests.exe : fatal error LNK1120: 1 unresolved externals
Could you please help me?
Q3. I don't need this but is there any way to have a base using CRTP class singleton in a multithreaded env?