在 init 方法中设置一个表示 init 成功的布尔值。在 getInstance 方法中,如果为 false,则抛出异常。
您可以将其作为静态私有成员存储在类中。
#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