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
2009-01-15 19:16:37
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
2009-01-15 23:15:38
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
2009-01-16 17:11:57
+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
2009-01-15 19:17:14
As Dmitriy Matveev pointed out below: don't neglect to protect the singleton against copying. See: boost::noncopyable.
John Watts
2009-01-15 20:39:18
"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
2009-01-15 21:04:05
ChrisW
2009-01-15 21:11:04
+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
2009-01-15 21:20:42
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
2010-01-07 19:16:00
+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
2009-01-15 19:19:29