三 单例模式、call_once使用

1. 单例模式

1)类构造函数私有化
2)拷贝构造、拷贝复制删除
3)使用静态类对象、静态类指针

#include<iostream>
#include <thread>
#include <mutex>
#include <string>

class Log_1
{
private:
    Log_1() {};
public:
    Log_1& operator= (const Log_1& log1) = delete;
    Log_1(const Log_1& log1) = delete;
    static Log_1& getInstance() {
        static Log_1 log1;
        return log1;
    }
    void print(const std::string& str) {
        std::cout << __TIME__ << " " << str << std::endl;
    }
};

class Log_2
{
private:
    Log_2(){};
public:
        Log_2(const Log_2& log) = delete;
        Log_2& operator= (const Log_2& log2) = delete;
        static Log_2& getInstance() {
            static Log_2* log2 = nullptr;
            if (!log2) log2 = new Log_2;
            return *log2;
        }
        void print(const std::string& str){
            std::cout << __TIME__ << " " << str << std::endl;
        }
}; 

void func() {
    Log_2::getInstance().print("error_2");
}

int main () {
    // Log_1::getInstance().print("error_1"); //懒汉模式
    // Log_2::getInstance().print("error_2"); //饿汉模式

    std::thread t1(func);
    std::thread t2(func);
    t1.join();
    t2.join();
}

2. call_once使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值