Skip to content

Instantly share code, notes, and snippets.

@trajano
Last active January 13, 2019 19:09
Show Gist options
  • Save trajano/e977a5c848a3419aea8c9a3f78bfc382 to your computer and use it in GitHub Desktop.
Save trajano/e977a5c848a3419aea8c9a3f78bfc382 to your computer and use it in GitHub Desktop.
C++ Singleton
#include <iostream>
#include "singleton.h"
int main()
{
std::cout << "Hello World!" << std::endl;
std::cout << Singleton::instance().singletonMethod() << std::endl;
}
#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;
}
#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