HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Thread-safe Singleton class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
singletonthreadsafeclass

Problem

I have created this class to simulate a thread-safe Singleton.

Have I missed anything?

#include 

class Singleton
{
public:
  static Singleton& GetInstance()
  {
    boost::mutex::scoped_lock lock(m_mutex);
    static Singleton instance;
    return instance;
  }

private:
  static boost::mutex m_mutex;

  Singleton() {}
  ~Singleton() {}

  Singleton(const Singleton&);
  const Singleton& operator=(const Singleton&);
};

Solution

As usual, when dealing with singletons, consider that you probably shouldn't be making a singleton at all.

Read this, for example. A singleton is almost certainly not what you actually need, even if it is implemented correctly and in a thread-safe manner.

A plain old global might be a better option, or perhaps you should simply pass a reference around to those who need it.

Context

StackExchange Code Review Q#6427, answer score: 2

Revisions (0)

No revisions yet.