gpt4 book ai didi

c++ - 与 get_instance() 分离的单例构造函数

转载 作者:行者123 更新时间:2023-11-30 04:21:05 24 4
gpt4 key购买 nike

在典型的单例中,构造函数在第一次调用 getInstance() 时被调用。我需要的是将 init 和 getInstance 函数分开。 init 函数必须创建实例 using constructor 并且 getInstance 只能在 init 函数被调用时使用(否则它会抛出异常)。我该怎么做?

    Singleton::init(required argument); //calls constructor
Singleton::getInstance(); //only possible if init had been called, otherwise throws exception

最佳答案

在 init 方法中设置一个 bool 值,表示 init 成功。在 getInstance 方法中,如果为假则抛出异常。

您可以将其作为静态私有(private)成员存储在类中。

#include <iostream>
class Single
{
public:
static void init(int x)
{
single.number = x;
inited = true;
}

static Single & GetInstance()
{
//Do exception stuff here....
if(inited)
{
std::cout << "Inited" << std::endl;
}
else
{
std::cout << "NOT Inited" << std::endl;
}
return single;
}


void printTest()
{
std::cout << single.number << std::endl;
}

private:
Single() : number(5)
{
std::cout << "Construction " << std::endl;
}

int number;
static bool inited;
static Single single;
};

bool Single::inited = false;
Single Single::single;

int main()
{
std::cout << "Entering main" << std::endl;

Single::GetInstance();
Single::init(1);
Single::GetInstance().printTest();

}

程序输出:

Construction 
Entering main
NOT Inited
Inited
1

关于c++ - 与 get_instance() 分离的单例构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14792286/

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