在真正需要使用的时候才进行构建,而不是在一开始就创建。如果要保证线程安全,需要使用一个mutex来保证。
#include
using namespace std;
class Single{
public:
static Single* getInstance(){
// if(pointer == nullptr){
// pointer = new Single();
// pointer->t = 10;
// }
return pointer;
}
void get(){
cout << t << endl;
}
~Single(){}
private:
Single(){};
int t = 0;
static Single* pointer;
};
// Single* Single::pointer = nullptr; // 饱汉式
Single* Single::pointer = new Single(); // 饿汉式
int main(){
auto p1 = Single::getInstance();
auto p2 = Single::getInstance();
cout << std::boolalpha << bool(p1 == p2) << endl;
return 0;
}