C++ singleton GetInstance() return

后端 未结 4 869
忘掉有多难
忘掉有多难 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:16

    I prefer a reference. I use reference instead of a pointer whenever I want to document that:

    • It can't be null
    • It won't be changed (to point to something else)
    • It mustn't be deleted
    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2021-02-05 13:29

    I think it would be safer to return a reference, but don't forget about "copy protection" of your singleton object.

    0 讨论(0)
  • 2021-02-05 13:31

    It doesn't matter aside from returning a reference implicitly guarantees that the singleton exists. (If it doesn't, you should throw an exception.)

    This also ignores the advice that singletons are evil as much as globals are evil since singletons are basically globals in design pattern clothing.

    0 讨论(0)
提交回复
热议问题