File: Singleton.hpp

package info (click to toggle)
yade 2023.02a-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 31,732 kB
  • sloc: cpp: 87,798; python: 48,852; sh: 512; makefile: 162
file content (26 lines) | stat: -rw-r--r-- 774 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 2005 Olivier Galizzi, Janek Kozicki
// 2009 © Václav Šmilauer <eudoxos@arcig.cz>
#pragma once

#include <mutex>

#define FRIEND_SINGLETON(Class) friend class Singleton<Class>;
// use to instantiate the self static member.
#define SINGLETON_SELF(Class) template <> Class* Singleton<Class>::self = NULL;
// one singleton cannot access another in its constructor.
namespace {
std::mutex singleton_constructor_mutex;
}
template <class T> class Singleton {
protected:
	static T* self; // must not be method-local static variable, since it gets created in different translation units multiple times.
public:
	static T& instance()
	{
		if (!self) {
			const std::lock_guard<std::mutex> lock(singleton_constructor_mutex);
			if (!self) self = new T;
		}
		return *self;
	}
};