User Tools

Site Tools


programming:cpp

C++

The Standard

Quality

Smart Pointers

Functors & Lambdas

Scoped Lock

Exceptions

Double-Checked Locking Pattern (DCLP)

Singleton

Singleton

Static Instance

A thread-safe method (guaranteed since C++11, see here) using a static instance of class CFoo (Meyers singleton):

class CFoo {
public:
  static CFoo& getInstance()
  {
    static CFoo instance;
    return instance;
  }
};

Dynamic, Using Smart Pointers

A thread-safe method using C++11 smart pointers for creation of an singleton instance of class CFoo:

#include <mutex>  // std::mutex
#include <memory> // std::weak_ptr, std::shared_ptr
 
using std;
 
static weak_ptr<CFoo> s_pFoo; // singleton instance pointer
static mutex s_lock;          // singleton instance lock
 
shared_ptr<CFoo> CFoo::getInstance()
{
  lock_guard<mutex> lock(s_lock);
  shared_ptr<CFoo> pInstance = s_pFoo.lock();
 
  if (!pInstance)
  {
    pInstance = make_shared<CFoo>(); // create shared smart pointer
    s_pFoo = pInstance;              // replace (set) managed object
  } // if
 
  return pInstance;
} // getInstance()

Dynamic, Using DCLP

1)
Old style “function pointers” based on polymorphism.
programming/cpp.txt · Last modified: 2021/04/20 10:39 by Ralf Hoppe