我想知道如何使用c ++检查运行时是否存在任何单个对象的实例。我当前对getInstance()方法的实现如下所示:
singletonclass* getInstance() {
if (pInstance == 0) {
pInstance = new singletonclass();
}
return pInstance;
}
问题是,如果不存在,该实现也将创建一个新实例。我只想在代码的某个特定点上创建一个实例。在我想要访问单例对象并且不存在任何其他部分的所有其他部分上,它应该抛出异常或类似的东西。 有人可以帮我这个吗?
答案 0 :(得分:0)
使用标记来微调行为:
singletonclass* getInstance(bool createIfNeeded = true) {
if (pInstance == 0 )
{
if createIfNeeded )
{
pInstance = new singletonclass();
}
else
{
throw MyException();
}
}
return pInstance;
}
在适当的时候致电singletonclass::getInstance(false);
。