I am trying to implement a singleton class that has to be used in two different threads, one sets up its member variables and the other one uses them, but the constructor is being called twice so I cannot use the members set in the first thread because they have their default value.
The implementation is quite standard, a static function that returns a reference to a static member in that function, I have tried to return a pointer, create a raw pointer and return it and the constructor always is called twice.
class Singleton
{
public:
static Singleton &getInstance()
{
static Singleton instance;
return instance;
}
// public methods
private:
Singleton();
Singleton(const Singleton &) = delete;
Singleton(Singleton &&) = delete;
Singleton &operator=(const Singleton &) = delete;
Singleton &operator=(Singleton &&) = delete;
// member variables
};
The thread trying to access to the singleton has been created using std::async(std::launch::async, lambda)
I expected that instance's constructor is called just the first time I call this function, but the second time instance has a different memory direction.