单例模式(C++)以及共享问题
发布日期:2021-05-10 01:23:25 浏览次数:19 分类:精选文章

本文共 2703 字,大约阅读时间需要 9 分钟。

C++���������������������std::call_once������

���C++���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������std::call_once������������������������������������

���������������������������

������������������������������������������������������������������������������������������������������������������������������������������������������������������

������������������������������Single���������������������������������������������������

class Single {
private:
Single();
public:
static Single* GetInstance() {
if (my_instance == nullptr) {
my_instance = new Single();
static DeleteObj d1;
}
return my_instance;
}
// ������������������
private:
static Single* my_instance;
};

���������������������my_instance������������������������������������������������nullptr���GetInstance()������������������my_instance������������������������������������������������������������������������������������������������������������������������GetInstance()������������������������������������

������������������������������������������������������������������������DeleteObj������������������������������my_instance���������������null���

class DeleteObj {
public:
~DeleteObj() {
if (Single::my_instance) {
delete Single::my_instance;
Single::my_instance = nullptr;
cout << "������" << endl;
}
}
};

������std::call_once���������������������������������

������������������������������������my_instance������������������������������������������GetInstance()������������������������������������������������������������������std::call_once���������������������������������������������������������������������������������������once_flag���������������������������

���������������������������

static void CreateInstance() {
my_instance = new Single();
static DeleteObj d1;
}
static Single* GetInstance() {
std::call_once(flag, CreateInstance);
return my_instance;
}

���������flag���������once_flag������������������������������������������������������������������������GetInstance()������std::call_once���������CreateInstance()���������������������������������������������������flag���������������������std::call_once������������������������������CreateInstance()������������������������������������������������������������

������

���������������������������������������������������������������������������������������std::call_once���������������������������������������������������������������������������������������������������������������������

上一篇:C++进制转换、字符串转数字
下一篇:C++11 多线程并发编程,thread,lock,lock_guard,unique_lock使用

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月16日 17时57分35秒