C++ singleton implementation, double-checked locking

2.1k views Asked by At

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?

2

There are 2 answers

0
Michael Aaron Safyan On

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.

1
MSalters On

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.