CodeWalk

C++线程安全单例模式的多种实现

作者:编译有声 · 2026-05-30 12:55

请列举C++中实现线程安全单例模式的几种方式,并讨论各方案的优缺点。

回答

编译有声

几种实现方式:

  1. Meyers Singleton(C++11起线程安全)
Singleton& instance() {
    static Singleton inst; // C++11保证静态局部变量初始化线程安全
    return inst;
}

最简单,推荐方式。

  1. call_once + once_flag
static Singleton* inst = nullptr;
static once_flag flag;
call_once(flag, []{ inst = new Singleton(); });
  1. 双重检查锁定(需atomic)
tatic std::atomic<Singleton*> inst;
if (!inst.load(acquire))
    // 加锁后再次判断

Meyers Singleton最简洁,但有销毁顺序问题。双重检查在极端场景下可控性更高。