Hi Everyone,
Crypto++ provides a Singleton class in misc.h. The original class suffered C++03 (and earlier) shortcomings. A design compromise was made to leak memory rather than using locks to increase portability.
We now have a portable implementation that does not depend on non-portable locks. It follows
http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11.
template <class T, class F, int instance>
const T & Singleton<T, F, instance>::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const
{
static std::mutex s_mutex;
static std::atomic<T*> s_pObject;
T *p = s_pObject.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (p)
return *p;
std::lock_guard<std::mutex> lock(s_mutex);
p = s_pObject.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (p)
return *p;
T *newObject = m_objectFactory();
s_pObject.store(newObject, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_release);
return *newObject;
}
The implementation is guarded by both
CRYPTOPP_CXX11_ATOMICS and CRYPTOPP_CXX11_SYNCHRONIZATION because
atomics is not a proper subset of synchronization when it comes to
compiler support and versions.
I'd like to merge it once it goes through a round of testing.
Are there any objections?
Jeff