实例化单例对象时,std :: system异常 [英] std::system Exception when instantiating a singleton object

查看:118
本文介绍了实例化单例对象时,std :: system异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在 c ++ 11 及更高版本中实现线程安全的单例模式。

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

我尝试使用 gdb 。似乎在调用 std :: call_once 时引发了异常。我不确定发生了什么,但我认为lambda表达式未能创建该对象。

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.

第二个问题。有没有办法知道未知错误代码的实际含义?我认为 -1 在尝试找出问题时无济于事。

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.

感谢您的帮助。

推荐答案

之所以会发生这种情况,是因为您没有使用 -pthread 标志进行编译,并且正在尝试使用系统上本机线程库中的实用程序。

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;
}

这是线程安全的,将导致实例变量仅初始化一次。这篇Wikipedia文章很好地解释了它如何在 https://en.wikipedia .org / wiki / Double-checked_locking 。最好让编译器尽可能为您安排代码。 也如评论所述这个问题也有有关上述> Meyers的Singleton模式线程实现的有用信息安全吗?

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?

这篇关于实例化单例对象时,std :: system异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆