有没有人用c++实现过单例?
有没有人用c++实现过单例? 我现在必须释放资源(因为未来随着项目的推进可能会在单例中加入大量GDI资源、Socket连接、File句柄等等),地球人都知道析构函数不行。
根据Modern c++ design的指示我使用了atexit注册,也不行,因为class成员是thiscall调用,而atexit是cdecl调用约定,很郁闷的是MCD著作大师戛然而止了(更别提GOF讲的Singleton了,简直是一笔代过),他给的代码明显不能编译通过。于是乎,我只能把释放函数也搞成了static,不让这个类成员它生成可恶的this指针参数!
下面的代码要加上锁解决多线程访问。
把释放函数搞成了static,那么资源也必须是static的,否则无法访问。
现在的问题是: 我把资源都搞成static吗? 这样做会带来哪些不良后果?项目计划把大量的全局量搞成单例。
static成员好像在程序退出时操作系统会做清理的,假如是一个位图句柄或者是打开着的文件句柄等等打开着的资源,不知道操作系统会不会把打开的资源关闭?
项目中打算使用的示例性代码:
#include <iostream>#include <cstdlib>using namespace std;// headerclass CGlobalGdiRes{private: static int h1,h2; //在这里声明所有资源,比如位图、字体等。 CGlobalGdiRes(){ h1=1;h1=2; //在这里创建所有资源。 cout<<"CGlobalGdiRes Constructed!"<<endl; }; ~CGlobalGdiRes(){}; static void Release(){ h1=0;h2=0; //在这里释放所有资源。 cout<<"All resources had been released!"<<endl; }; CGlobalGdiRes(const CGlobalGdiRes&){}; CGlobalGdiRes& operator=(const CGlobalGdiRes&){}; static CGlobalGdiRes* pIns;public: static CGlobalGdiRes* GetInstance() { if (!pIns) { if (!pIns) { pIns =new CGlobalGdiRes; atexit(&CGlobalGdiRes::Release); } } return pIns; }protected:};// implementCGlobalGdiRes* CGlobalGdiRes::pIns=0;int CGlobalGdiRes::h1 =0;int CGlobalGdiRes::h2 =0;//driverint main(){ CGlobalGdiRes* p =CGlobalGdiRes::GetInstance(); return 0;}