0

I heard and read a lot about singleton implementation approaches in C++, like Meyer, Phoenix, etc., but all of them seemed to have a problem in certain usage scenarios. So I came up with my own implementation approach, the Daniel Singleton. What I would like to know is if it's correct or not... I think it is, but please tell me if it has any flaws I did not think of!

Also, I tried to make it thread-safe without acquiring locks all the time by using double-checked locking, which I read a lot about too, and everybody stated that it's broken. I tried to fix that too, and I'd like to know if my solution is correct or not... and if it's not, then how can it fail?

  • I'd guess you got downvoted because this isn't a self-contained question. If you posted the smallest possible snippets of your code here and asked if they were correct, you might get a better response, or you could post them on the sister site specific to code review. I looked at the page you linked, but it's a lot of code--so much that I wouldn't want to use it for something that should be simple (or not done at all). – John Zwinck Feb 13 '11 at 21:23
  • Also, the topic of singletons is pseudo-religious. Some people swear by it, and some swear at it. I'm somewhere in between. For smaller projects, I find it to be useful, as it hides initialization of global variables (singleton is just another name for global variables). For larger projects, I find it to be quite bad. It's hard to test (unit tests), and its hard to make it thread safe. – Jörgen Sigvardsson Feb 13 '11 at 21:55
  • 1
    @Jorgen: "singleton is just another name for global variables" No it's not, singletons cannot be copied. – GManNickG Feb 14 '11 at 05:55
  • So they're const global variables. Big deal...? – Jörgen Sigvardsson Feb 14 '11 at 07:49
  • 1
    @Jorgen: You can copy const objects. – GManNickG Feb 14 '11 at 16:47

2 Answers2

4

The singleton pattern, itself, is broken in that it makes for horrible code. It's really much better to use dependency injection / inversion of control. See my page on avoiding singletons here.

Your singleton class is needlessly complicated. It looks like you are implementing the lazy singleton pattern, and you are still acquiring a lock, so -- aside from making things needlessly convoluted -- I'm not sure how what you are doing is much different from simpler lazy singleton implementations. Have you benchmarked your implementation to determine if it is any faster than the simpler alternatives? I would want to see a clear performance win to go with something that is way more complicated.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
1

The double-checked locking pattern is like ascii and IEE754 floating points. It's fairly safe to assume that it works well enough on every system you'll ever see, even though it's not formally guaranteed.

MSalters
  • 173,980
  • 10
  • 155
  • 350