std::system Exception when instantiating a singleton object

别说谁变了你拦得住时间么 提交于 2019-12-12 19:11:26

问题


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.


回答1:


This happens because you did not compile with the -pthread flag and are attempting to use utilities from the native threading library on your system.

As an alternative look into the following change to the singleton pattern definition in your example referred to as the "Meyers Singleton"

Singleton& Singleton::get_instance(){
    static Singleton instance;
    return instance;
}

This is thread safe, and will cause the instance variable to only be initialized once. This wikipedia article has a good explanation of how it possibly works under the hood https://en.wikipedia.org/wiki/Double-checked_locking. It is good to let the compiler arrange code for you whenever possible. Also as noted in the comments this question also has useful information about the above Is Meyers' implementation of the Singleton pattern thread safe?



来源:https://stackoverflow.com/questions/44653808/stdsystem-exception-when-instantiating-a-singleton-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!