单例初始化两次,std :: call_once也运行两次

问题描述

我有以下简单的单例代码,std :: call_once只是为了确保一切正常,我打算在工作后立即将其删除

std::once_flag flag1;

ProfileModel* ProfileModel::instance()
{
    std::call_once(flag1,[](){ qDebug() << "Simple example: called once\n"; });
    static ProfileModel self;
    qDebug() << &self ;
    return &self;
}

看起来很简单,从我对C ++的了解来看,这应该可行。但是此调用返回了两个指针,call once也打印两次。

Simple example: called once
Constructing Konsole::ProfileModel(0x7ff7378a31f0)
Simple example: called once
Constructing Konsole::ProfileModel(0x5592aeb87160)

我唯一不确定的是,我将其存储在静态库中,并且只在主应用程序中两次调用该库,一次在该库内部,一次在外部。 / p>

任何人都可以分享一点光吗?

解决方法

它是Static variable is initialized twice的副本,不同之处在于它不是静态变量,而是具有静态变量的方法。