gpt4 book ai didi

带参数的 C++ Meyer 单例

转载 作者:行者123 更新时间:2023-12-05 06:20:18 26 4
gpt4 key购买 nike

是否可以使用参数定义 Meyer 的单例(如 this one)?

我知道 GOF 风格的单例(如 here )是可能的,

但我似乎无法让它与 Meyer 的单例一起工作:

// ...
public:

static S& getInstance()
{
static S instance; // no way to pass arguments here ...
return instance;
}

编辑:

我想要一个 Init 函数和多个 getInstance。所以典型的用法是这样的:

S::Init(5, 6.4);
foo(S::getInstance());
bar(S::getInstance());

最佳答案

您可以只将初始化参数存储在静态中。示例:

class S {
public:
static void Init(int i)
{
i_ = i;
initialized_ = true;
}

static S& getInstance()
{
if (!initialized_) {
throw SomeException;
}
static S instance(i_);
return instance;
}

private:
S(int) { }

static int i_;
static bool initialized_;
};

请记住在实现 (.cpp) 文件中实际定义静态:

int S::i_ = 0;
bool S::initialized_ = false;

显然,您也可以对这些使用 Meyer 单例,但由于它们是内置类型并且不依赖于其他数据,因此您不会真正获得太多。

关于带参数的 C++ Meyer 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60575118/

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