本代码采用饿汉模式,是线程安全的,而且静态对象在生命周期结束的时候也会自动析构。
#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"
网友评论