Skip to content

Instantly share code, notes, and snippets.

@abelardojarab
Created November 7, 2017 22:14
Show Gist options
  • Save abelardojarab/b2941cb2402528a69a532caedd66bba9 to your computer and use it in GitHub Desktop.
Save abelardojarab/b2941cb2402528a69a532caedd66bba9 to your computer and use it in GitHub Desktop.
Create singleton class in C++
// Example program
#include <iostream>
#include <string>
#include <memory>
class singleton
{
static std::shared_ptr<singleton> instance(int a)
{
if (!instance_)
{
instance_.reset(new singleton(a));
}
return instance_;
}
private:
singleton(int a);
static std::shared_ptr<singleton> instance_;
};
std::shared_ptr<singleton> singleton::instance_(0);
int main()
{
auto s = singleton::instance();
std::string name;
std::cout << "What is your name? ";
getline (std::cin, name);
std::cout << "Hello, " << name << "!\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment