《Effective C++》条款4中说要确定对象被使用之前已被初始化。
我现在win32程序有一个对象,将它设计为单例,但是它构造时需要传入hinstance和title参数进行构建。
我的做法是:
//winmain.cpp
RPhoton* RPEngine = RPhotonEngine::RPEngine(hInstance, L"RPhoton");
//RPhotonEngine.h
class RPhotonEngine
{
public:
static RPhoton* RPEngine(HINSTANCE hinstance, std::wstring title);
static RPhoton* RPEngine();
protected:
RPhotonEngine();
private:
static RPhoton* g_RPhoton;
};
//RPhotonEngine.cpp
RPhoton* RPhotonEngine::g_RPhoton = nullptr;
RPhoton* RPhotonEngine::RPEngine(HINSTANCE hinstance, std::wstring title)
{
if (g_RPhoton == nullptr)
{
g_RPhoton = new RPhoton(hinstance, title);
}
return g_RPhoton;
}
RPhoton* RPhotonEngine::RPEngine()
{
return g_RPhoton;
}
RPhotonEngine::RPhotonEngine()
{
}
感觉这样做怪怪的,怎么改比较好??
迷茫2017-04-17 13:16:19
class SomeEngine{
public:
RPhoton* getInstance(HINSTANCE hinstance, std::wstring title){
//check if hinstance or title is legal
//then return the static instance
static RPhoton* somePhoton = new RPhoton(hinstance, title);
return somePhoton;
}
protected:
SomeEngine(){}
};
C++ guarantees that the static variable in getInstance will only be initialized once.
伊谢尔伦2017-04-17 13:16:19
If you want to use a singleton and pass parameters, you can only add an Init function to pass parameters. The singleton still gets the instance of the object, but it is actually initialized during Init.
Reference class两阶段构造
https://msdn.microsoft.com/library/7ffyb1kb%28v=vs.110%29.aspx