I am having problems with my singleton pattern implementation in MSVC ++ 17 version 15.5.5. I am compiling a flag /std:c++17.
My implementation consists of the following helper class:
#pragma once
#include <cassert>
template<class T>
class Singleton : private T
{
public:
virtual ~Singleton() = default;
template<typename ... Targs>
static T & initInstance(Targs && ... args)
{
assert(instance == nullptr);
instance = new Singleton<T>(std::forward<Targs>(args)...);
return *instance;
}
static T & getInstance()
{
assert(instance != nullptr);
return *instance;
}
private:
template<typename ... Targs>
explicit Singleton(Targs && ... args)
: T{ std::forward<Targs>(args)... }
{}
static T * instance;
};
template<class T>
T * Singleton<T>::instance = nullptr;
, , if, , getInstance(). , , if . initInstance(), , getInstance(). , assert() , .
:
#include "Singleton.h"
#include <iostream>
class Foo
{
public:
virtual ~Foo() = default;
protected:
Foo(int i)
: i{ i }
{
std::cout << "foo ctr " << i << "\n";
}
private:
int i;
};
int main(int argc, char** argv)
{
Singleton<Foo>::initInstance(5);
Foo & theOnlyFoo = Singleton<Foo>::getInstance();
return 0;
}
:
Singleton<Foo>::initInstance(); - , Foo , . , Singleton<Foo> , Foo , . - .
, Singleton<Foo>, Foo . , instance datamember i, , , Foo .
, Foo . , Foo .