User Tools

Site Tools


programming:cpp

Table of Contents

C++

Overview

Smart Pointers

Lambdas & Functors

Polymorphism

Singleton

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()
programming/cpp.txt · Last modified: 2016/09/19 19:23 by Ralf Hoppe