具有只读和写入访问权限的单例

Singleton with read-only and write access

我有一个 class T 并且想要 class 的单个全局对象,由 T const& read_singleton()T& modify_singleton() 等访问函数给出。该对象应该在 T 的默认构造函数首次使用其中一个函数时实例化,并且这些函数的使用应该是线程安全的。实现这一目标的(好的)设计模式是什么?

编写这些函数很容易:

T& modify_singleton()
{
    T static t{};
    return t;
}

T const& read_singleton()
{
    return modify_singleton();
}

这是 Meyers 单例模式,也可以作为 T 的静态函数实现,以防您可以控制其实现并希望将其 constructor/destructor 等设为私有。

变量t的初始化为thread-safe。但是,当多个线程获得 T& 时会发生什么,这超出了 modify_singleton 的控制范围。您将不得不协调对对象的修改,使用全局互斥锁或通过将其 class 设计为 thread-safe。如果你不能修改 class T,你也可以通过包装器 class.

提供一个 thread-safe 接口