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?
I prefer a reference. I use reference instead of a pointer whenever I want to document that:
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/
I think it would be safer to return a reference, but don't forget about "copy protection" of your singleton object.
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.