Last active
January 13, 2019 19:09
-
-
Save trajano/e977a5c848a3419aea8c9a3f78bfc382 to your computer and use it in GitHub Desktop.
C++ 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 <iostream> | |
#include "singleton.h" | |
int main() | |
{ | |
std::cout << "Hello World!" << std::endl; | |
std::cout << Singleton::instance().singletonMethod() << std::endl; | |
} |
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 <iostream> | |
#include "singleton.h" | |
Singleton::Singleton(const char* message) { | |
std::cout << "Singleton Initialized" << std::endl; | |
this->message = message; | |
} | |
Singleton::~Singleton() { | |
this->message = "If you see this you have threads that are still running after the singleton is destroyed"; | |
std::cout << "Singleton destroyed" << std::endl; | |
} | |
const char* Singleton::singletonMethod() { | |
return message; | |
} | |
Singleton& Singleton::instance() { | |
static Singleton theInstance("My message from singleton constructor"); | |
return theInstance; | |
} |
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
#pragma once | |
class Singleton { | |
private: | |
const char* message; | |
Singleton(const char* message); | |
~Singleton(); | |
public: | |
static Singleton& instance(); | |
const char* singletonMethod(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment