I'm learning how to implement a thread safe singleton pattern in c++11
and later.
#include <iostream>
#include <memory>
#include <mutex>
class Singleton
{
public:
static Singleton& get_instance();
void print();
private:
static std::unique_ptr<Singleton> m_instance;
static std::once_flag m_onceFlag;
Singleton(){};
Singleton(const Singleton& src);
Singleton& operator=(const Singleton& rhs);
};
std::unique_ptr<Singleton> Singleton::m_instance = nullptr;
std::once_flag Singleton::m_onceFlag;
Singleton& Singleton::get_instance(){
std::call_once(m_onceFlag, [](){m_instance.reset(new Singleton());});
return *m_instance.get();
};
void Singleton::print(){
std::cout << "Something" << std::endl;
}
int main(int argc, char const *argv[])
{
Singleton::get_instance().print();
return 0;
}
The code compiles fine but when executing i receive the following Exception.
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted
i tried to debug the program with gdb
. It seems that the exception is thrown when calling std::call_once
. I'm not sure about what's happening but i assume that the lambda expression failed to create the object.
A second question. Is there a way to know what unknown error codes actually mean ? i think a -1
will not help much when trying to identify the problem.
Thanks for your help.