1

someone told me just to write singleton as a local class, is that true?

I am wondering why using the local class can ensure thread safety.

Adam Lee
  • 24,710
  • 51
  • 156
  • 236

2 Answers2

1
#include <boost/utility.hpp>

class singleton : private boost::noncopyable {
public:
    static singleton& instance() {
        static singleton inst;
        return inst;
    }

private:
    singleton() = default;
    ~singleton() = default;
};

The construction of local static variables is guaranteed to be thread-safe.

Also, avoid singletons at all cost. They are just as terrible as globals are.

  • Almost equivalent as the example in the article mentioned above written for C. Voted you up. – Peter Jan 19 '14 at 03:59
0

Take a look at this post: what is correspoding feature for synchronized in java?
feature-for-synchronized-in-java
Basically it states that C++ doesn't has a language level feature for locking mechanisms,
wich you need to make your singelton class threadsafe, though this articel
http://en.wikipedia.org/wiki/Double-checked_locking about the Double Checked Locking Pattern
states, that no locking is needed for singletons (an example is included for c).

Community
  • 1
  • 1
Peter
  • 1,769
  • 1
  • 14
  • 18