Skip to content

Instantly share code, notes, and snippets.

@SwarajKetan
Created October 20, 2020 04:32
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 SwarajKetan/f6760638961c8e7f3dd28aff5fbb3013 to your computer and use it in GitHub Desktop.
Save SwarajKetan/f6760638961c8e7f3dd28aff5fbb3013 to your computer and use it in GitHub Desktop.
Nice way to implement thread-safe singleton pattern with enhanced security
#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