C++ singleton GetInstance() return

后端 未结 4 868
忘掉有多难
忘掉有多难 2021-02-05 12:46

When implementing a singleton in C++, is it better for GetInstance() to return a pointer to the singleton object, or a reference? Does it really matter?

4条回答
  •  别那么骄傲
    2021-02-05 13:22

    The getInstance() method returns a reference since the function-static object is initialized when the control flow is first passing its definition.Also working with a reference is better: now user can not delete the singleton’s pointer. In addition, this implementation is so simple!

    class CKeyboard
    {
    public:
        static CKeyboard& GetInstance()
        {
            static CKeyboard keyboard;
            return keyboard;
        }
    
    private:
        CKeyboard() {}
        CKeyboard(const CKeyboard&);
        CKeyboard& operator=(const CKeyboard&);
    };
    

    http://www.devartplus.com/3-simple-ways-to-create-singleton-in-c/

提交回复
热议问题