gpt4 book ai didi

java - Java 中的单例与 C++ 中的单例

转载 作者:行者123 更新时间:2023-11-30 01:18:15 33 4
gpt4 key购买 nike

在 Java 中,我可以像这样创建一个单例(只要它不作为异常抛出):

private static Singleton m_this = new Singleton();

这非常方便,因为它本质上是线程安全的。

我可以用 C++ 做类似的事情吗?

最佳答案

一种使用线程安全初始化创建单例的方法,由 C++11 的标准保证。是:

class SomeSingleton {
public:
static SomeSingleton& instance() {
static SomeSingleton instance_;
return instance_;
}

private:
SomeSingleton() {
...
}
};

这是线程安全的,因为 local static variable initialization is thread-safe in C++11 .相关标准文件,N3485 , 在第 6.7.4 节中说:

such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. [...] If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

带脚注:

The implementation must not introduce any deadlock around execution of the initializer.

您可以使用 CRTP 抽象成一个漂亮的模板基类:

//Singleton template definition
template <typename TDerived>
class Singleton {
static_assert(is_base_of<Singleton, TDerived>::value, "Singleton: unexpected Derived template parameter");
public:
static TDerived& instance() {
static TDerived instance_;
return instance_;
}

protected:
Singleton() {
}
};

// SomeSingleton definition, using the Singleton template
class SomeSingleton : public Singleton<SomeSingleton> {
...
};

关于java - Java 中的单例与 C++ 中的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22902314/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com