首页 > C++中单例模式构造对象时需要传参数应该怎么做?

C++中单例模式构造对象时需要传参数应该怎么做?

《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()
{
}

感觉这样做怪怪的,怎么改比较好??


又要用单例, 又要传参, 那你只能增加一个Init函数, 用来做传参的动作了. 单例还是获取对象的实例, 只是Init的时候才真正的初始化.

参考类的两阶段构造
https://msdn.microsoft.com/library/7ffyb1kb%28v=vs.110%29.aspx


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++保证getInstance里的static变量只会被初始化一次。

【热门文章】
【热门文章】