views:

1984

answers:

3

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?

A: 

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.

MSN

MSN
I do maintain that singletons have legitimate uses, and an active developer working on varied software might well want one every decade of so.
David Thornley
Every use of singleton is an admission that you don't expect your code to scale in a particular direction. At least that's what I've found to be true.MSN
MSN
+22  A: 

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
ChrisW
As Dmitriy Matveev pointed out below: don't neglect to protect the singleton against copying. See: boost::noncopyable.
John Watts
"See boost::noncopyable", or just declare a private copy constructor and assignment operator. Yes, there are some other issues around singletons: for example, do they 'smell', are they thread-safe, are they constructed in the right sequence: I ws only trying to answer the actual question in the OP.
ChrisW
ChrisW
+1 good answer. I want to add that the singleton object should be protected against copying regardless of whether you return a pointer or reference ... but I agree its much easier to accidentally copy it as a reference.
Brian Ensink
See the Meyers section on page 5 of this article (C++ In Theory: The Singleton Pattern, Part I) on the use of references: http://www.devarticles.com/c/a/Cplusplus/C-plus-plus-In-Theory-The-Singleton-Pattern-Part-I/
dwj
+5  A: 

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

Dmitriy Matveev
+ 1 for bringing up 'copy protection'