Last active
June 5, 2020 18:54
-
-
Save plusangel/437fe1772cd16714986b855547724da6 to your computer and use it in GitHub Desktop.
Singleton idiom example in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "singleton.h" | |
#include <iostream> | |
static Singleton &singleton = Singleton::GetInstance(); | |
int main() { | |
std::cout << "Hello, World!" << std::endl; | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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; | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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