Archive

Posts Tagged ‘singleton’

Watch Out For Multipletons

September 26, 2010 2 comments

Because C++ has both pointers and references, there are two ways to implement a singleton. The programs below show the difference between the approaches (I know, I know. I could’ve used a smart pointer on the left). Since references can’t be “accidently” deleted by client code, I prefer the reference method on the right. Plus, there’s no need for an “if” test every time the singleton’s handle is retrieved by client code.

When using a singleton, don’t forget to put the definition of the “instance()member function (or the pointer definition) into a separate .cpp implementation file, and not as an inline in the .h file. Otherwise, each .cpp file in your program that needs to access the singleton will get it’s own personal copy of a singleton, transforming it into a “multipleton”. You’ll get a program that compiles but has a subtle, hard to detect runtime bug that won’t crash the program.

And yes, we found this out the hard way. 🙂

Post-picture insertion notes: 1) I shoulda named the variables in the main() of the pointer version of the singleton sPtr1 and sPtr2. 2). For consistency, I prolly shoulda made the copy assignment operator function private in both implementations. Is there anything else I could do to improve the code?

Categories: C++ Tags: , ,