单例模式,无故析构的问题

xdh0817 2014-04-14 10:43:32

类的定义:
template<class T>
class SingletonT
{
public:
static T* Instance()
{
static SingletonT single;
if (0 == single._instance.get())
{cout<<"0 == single._instance.get()"<<endl;
single._instance.reset(new T);
}
return single._instance.get();
}
virtual ~SingletonT(void){cout<<"~single"<<endl; _instance.reset(NULL);};

private:
SingletonT(void){};
SingletonT(const SingletonT&){}
SingletonT& operator=(const SingletonT&){}
auto_ptr<T> _instance;
};

namespace svcctrl
{
class ModuleStatusCheck : public CheckThread
{
public:
ModuleStatusCheck(void);
~ModuleStatusCheck(void);
virtual void Check();
private:
ModuleStatusCheck(const ModuleStatusCheck& other);
ModuleStatusCheck & operator = (const ModuleStatusCheck& other);
DECLARE_SINGLETON_CLASS(ModuleStatusCheck);
};
typedef SingletonT<ModuleStatusCheck> SModuleStatusCheck;
}


使用:
int main()
{
SModuleStatusCheck::::Instance()->Start();//创建线程,执行一些数据库任务
while(true)
{
cout<<"in while"<<endl;
sleep(1);
}
return 0;
}

问题:在数据库切换的时候,析构了,打印:~single ~ModuleStatusCheck ~CheckThread
线程监测到析构,于是线程自身按照正常流程结束,最后这个int main()就无奈的陷在了while(true)里。
既然main没有结束,那么我的单例为什么会析构呢!!!!!!!!!!!!!!!!

...全文
145 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
LiuYinChina 2014-04-14
  • 打赏
  • 举报
回复
auto_ptr<T>
易流洋 2014-04-14
  • 打赏
  • 举报
回复
有些地方没改,有误,知道我的意思就行。
易流洋 2014-04-14
  • 打赏
  • 举报
回复
感觉不像正规的单例模式, public: static T* Instance() { if (0 == single._instance.get()) {cout<<"0 == single._instance.get()"<<endl; single = new Singleton(); } return single; } virtual ~SingletonT(void){cout<<"~single"<<endl; _instance.reset(NULL);}; private: static SingletonT single = NULL; SingletonT(void){}; SingletonT(const SingletonT&){} SingletonT& operator=(const SingletonT&){} auto_ptr<T> _instance; };
昵称很不好取 2014-04-14
  • 打赏
  • 举报
回复
在析构函数里弄个断点,看看什么地方调用了
lanlvy 2014-04-14
  • 打赏
  • 举报
回复
单例模式应该没写对

23,125

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧