Marcin
Marcin

Reputation: 12620

C++ singleton GetInstance() return

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?

Upvotes: 18

Views: 11851

Answers (4)

raj
raj

Reputation: 1

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/

Upvotes: 0

MSN
MSN

Reputation: 54634

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.

Upvotes: 1

okutane
okutane

Reputation: 14260

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

Upvotes: 10

ChrisW
ChrisW

Reputation: 56123

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

Upvotes: 38

Related Questions