实例化单例对象时的 std::system 异常

汉尼拔

我正在学习如何在以后实现线程安全的单例模式c++11

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

代码编译得很好,但在执行时我收到以下异常。

terminate called after throwing an instance of 'std::system_error'
what():  Unknown error -1
Aborted

我试图用gdb. 好像是调用的时候抛出了异常std::call_once我不确定发生了什么,但我认为 lambda 表达式未能创建对象。

第二个问题。有没有办法知道未知错误代码的实际含义?我认为-1在尝试确定问题时不会有太大帮助。

谢谢你的帮助。

好奇的

发生这种情况是因为您没有使用该-pthread标志进行编译,而是尝试使用系统上本机线程库中的实用程序。

作为另一种方式查看您的示例中的单例模式定义的以下更改,称为“迈耶斯单例”

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

这是线程安全的,并且会导致instance变量只被初始化一次。这篇维基百科文章很好地解释了它如何在幕后工作https://en.wikipedia.org/wiki/Double-checked_locking最好让编译器尽可能为您安排代码。同样如评论中所述,这个问题也有关于上述的有用信息Meyers 对单例模式线程的实现是否安全?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将System :: String转换为std :: string时,std :: string删除运算符中的运行时异常

如何将std :: system_error异常与std :: errc值进行可移植比较?

将对象移入std :: vector时的异常保证

如何处理实例化类对象时发生的异常

尝试在单例初始化期间发送异步获取请求时发生异常

由函数指针初始化的 std::function 的异常安全

当 RTC_DCHECK_IS_ON 时 WebRTC std::deque 迭代器异常

创建 QQuickWidget 时的 std::bad_alloc 异常

从opencv imencode删除std :: vector <unsigned char>时发生异常

调用 std::call_once 时出现异常

未处理的异常。System.NullReferenceException:对象引用未设置为对象的实例

我如何摆脱错误system.null引用异常对象引用未设置为对象的实例

异常:System.NullReferenceException:“对象引用未设置为对象的实例。”

通过std :: system调用python时出错

读取json文件异常“未处理的异常:System.TypeInitializationException:类型初始化程序”

使用Autofac访问单例时出现Null Reference异常

访问未初始化的元素时,std向量不会引发out_of_range异常

C ++ 11 std :: thread join在Xcode 6上崩溃并带有system_error异常和SIGABRT吗?

使用System.Text.Json.Serialization将动态对象转换为json时引发异常

来自std :: promise的未知异常

std :: regex构造抛出异常

std :: is_invocable的异常行为

std::vector<>.size() 抛出异常

std :: map :: operator []表现异常

std :: thread和异常处理

如何修复异常:无法将“System.DBNull”类型的对象转换为“System.Byte[]”类型

实例化JavaStreamingContext时出现AbstractMethodError异常

初始化安装时发生异常:System.BadImageFormatException:无法加载文件或程序集

当缺少属性时,如何强制System.Text.Json序列化程序引发异常?