Home > C++ > Watch Out For Multipletons

Watch Out For Multipletons

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: , ,
  1. September 30, 2010 at 12:06 am

    Your singleton isn’t thread-safe. Static variables shouldn’t be used if this singleton is intended for more than one thread to be accessed.

    Here’s an example on why static is bad for threading.
    http://blogs.msdn.com/b/oldnewthing/archive/2004/03/08/85901.aspx

    • September 30, 2010 at 3:38 am

      Yes, you’re right Alan. Thread safety isn’t the topic, avoiding multiple copies of a singleton is.

      Thread safety could be added by locking and unlocking a mutex within each publicly accessible function, no? In the example above, locking a mutex before the “cout” statement and unlocking it after would do the trick, right?

      We have a thread-safe singleton in our utility library that serializes access from multiple threads to the single std::cout resource. It’s better than wrapping each call to std::cout in a lock/unlock function pair throughout all the threads.

      Thanks for pointing this out. With multi-core servers taking over, thread safety is hugely important these days.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: