面试题2:C++ 单例模式最简单最安全实现
2018-11-08 本文已影响0人
修司敦
本代码采用饿汉模式,是线程安全的,而且静态对象在生命周期结束的时候也会自动析构。
#include <cstdlib>
#include <cstdio>
#include <iostream>
class Singleton {
private:
Singleton() { std::cout << "ctor" << std::endl; }
~Singleton() { std::cout << "dtor" << std::endl; }
static Singleton one;
public:
static Singleton *getInstance() { return &one; }
};
Singleton Singleton::one;
int main()
{
Singleton *one = Singleton::getInstance();
Singleton *two = Singleton::getInstance();
if (one == two) std::cout << "same instance!" << std::endl;
else std::cout << "Not the same!" << std::endl;
return 0;
}
//"ctor"
//"same instance!"
//"dtor"