Created
October 20, 2020 04:32
-
-
Save SwarajKetan/f6760638961c8e7f3dd28aff5fbb3013 to your computer and use it in GitHub Desktop.
Nice way to implement thread-safe singleton pattern with enhanced security
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 <ctime> | |
#include <chrono> | |
class Singleton | |
{ | |
private: | |
Singleton() { } | |
void operator delete(void*) {}; // such that its not deleted accidentally | |
public: | |
Singleton(Singleton&) = delete; // Copy prohibited | |
void operator=(const Singleton&) = delete; // Assignment prohibited | |
Singleton& operator=(Singleton&&) = delete; // Move assignment | |
static Singleton* getInstance(); | |
// This is a sample method | |
std::chrono::system_clock::time_point getTime() const { | |
auto now = std::chrono::system_clock::now(); | |
return now; | |
}; | |
}; | |
Singleton* Singleton::getInstance() { | |
static Singleton* pInstance_; | |
return pInstance_; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment