#include <stdio.h>
template <typename T>
class Singleton
{
public:
static T &GetInstance()
{
static T instance;
return instance;
}
protected:
Singleton() = default;
private:
// Delete copy/move so extra instances can't be created/moved.
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
Singleton(Singleton &&) = delete;
Singleton &operator=(Singleton &&) = delete;
};
class TestSingleton : public Singleton<TestSingleton>
{
public:
void print() { printf("%p TestSingleton\n", this); }
private:
TestSingleton() = default;
friend class Singleton<TestSingleton>;
};
inline TestSingleton &GetTestSingleton()
{
printf("func TestSingleton\n");
return TestSingleton::GetInstance();
}
int main()
{
// should not work.
TestSingleton().print();
GetTestSingleton().print();
GetTestSingleton().print();
GetTestSingleton().print();
// not work as expected
// TestSingleton test_copy = GetTestSingleton();
return 0;
}
how to forbiden TestSingleton instance out of Singleton, except writeprivate: TestSingleton() = default; friend class Singleton<TestSingleton>;
. anyone has good idea?
related articles following:https://en.wikipedia.org/wiki/Singleton_pattern