Skip to content

Instantly share code, notes, and snippets.

@plusangel
Last active June 5, 2020 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plusangel/437fe1772cd16714986b855547724da6 to your computer and use it in GitHub Desktop.
Save plusangel/437fe1772cd16714986b855547724da6 to your computer and use it in GitHub Desktop.
Singleton idiom example in C++
cmake_minimum_required(VERSION 3.16)
project(singleton_idiom)
set(CMAKE_CXX_STANDARD 17)
add_library(singleton singleton.cpp)
add_executable(singleton_idiom main.cpp)
target_link_libraries(singleton_idiom singleton)
#include "singleton.h"
#include <iostream>
static Singleton &singleton = Singleton::GetInstance();
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
//
// Created by angelos on 03/06/2020.
//
#include "singleton.h"
Singleton &Singleton::GetInstance() {
std::mutex mutex;
std::scoped_lock lock(mutex);
static Singleton instance;
return instance;
}
//
// Created by angelos on 03/06/2020.
//
#ifndef SINGLETON_IDIOM_SINGLETON_H
#define SINGLETON_IDIOM_SINGLETON_H
#include <mutex>
#include <thread>
class Singleton {
public:
static Singleton &GetInstance();
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
Singleton(Singleton&& ) = delete;
Singleton& operator=(Singleton&& ) = delete;
private:
Singleton() = default;
~Singleton() = default;
};
#endif//SINGLETON_IDIOM_SINGLETON_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment