#include <iostream>
#include <memory>
#include <mutex>
class Singleton
{
public:
typedef std::shared_ptr<Singleton> Ptr;
~Singleton()
{
std::cout << "destructor called!" << std::endl;
}
Singleton(Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Ptr get_instance()
{
if (m_instance_ptr == nullptr)
{
std::lock_guard<std::mutex> lk(m_mutex);
if (m_instance_ptr == nullptr)
{
m_instance_ptr = std::shared_ptr<Singleton>(new Singleton);
}
}
return m_instance_ptr;
}
private:
Singleton()
{
std::cout << "constructor called!" << std::endl;
}
static Ptr m_instance_ptr;
static std::mutex m_mutex;
};
Singleton::Ptr Singleton::m_instance_ptr = nullptr;
std::mutex Singleton::m_mutex;
int main()
{
Singleton::Ptr instance1 = Singleton::get_instance();
Singleton::Ptr instance2 = Singleton::get_instance();
return 0;
}
#include <iostream>
class Singleton1{
public:
~Singleton1()
{
std::cout << "destructor called!" << std::endl;
}
Singleton1(const Singleton1&) = delete;
Singleton1& operator=(const Singleton1&) = delete;
static Singleton1& get_instance()
{
static Singleton1 instance;
return instance;
}
private:
Singleton1()
{
std::cout << "constructor called!" << std::endl;
}
};
int main(int argc, char* argv[])
{
Singleton1& instance_1 = Singleton1::get_instance();
Singleton1& instance_2 = Singleton1::get_instance();
return 0;
}
#include <iostream>
using namespace std;
class Singleton2{
private:
static Singleton2* pInstance;
Singleton2()
{
cout << "constructor called!" << std::endl;
}
Singleton2(const Singleton2&) = delete;
Singleton2& operator = (const Singleton2&) = delete;
public:
static Singleton2* getInstance();
~Singleton2()
{
std::cout << "destructor called!" << std::endl;
}
void print()
{
cout << "this = " << this << endl;
}
};
Singleton2* Singleton2::pInstance = new Singleton2;
Singleton2* Singleton2::getInstance()
{
return pInstance;
}
int main()
{
Singleton2* s1 = Singleton2::getInstance();
Singleton2* s2 = Singleton2::getInstance();
s1->print();
s2->print();
return 0;
}
|