Created
November 7, 2017 22:14
-
-
Save abelardojarab/b2941cb2402528a69a532caedd66bba9 to your computer and use it in GitHub Desktop.
Create singleton class in C++
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
// 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