物是人非事事休,欲语泪先流|

游客0721

园龄:2年粉丝:4关注:2

小项目

搁置,暂时

1. 单例类封装

网络请求类要做成一个单例类,这样方便在任何需要发送http请求的时候调用,我们先实现单例类,添加singleton.h实现如下
关键词:单例的实践 protect封装 模版 静态 拷贝构造重载 智能指针冲突 析构函数的访问作用域 头文件的包含
image

单例类封装
#include <memory>
#include <mutex>
#include <iostream>
using namespace std;
template <typename T>
class Singleton {
protected:
//单例类的构造函数肯定是不能被外部访问的,但是为了能被子类构造所以设置成protect
Singleton() = default;
//不允许被拷贝构造拷贝赋值和重载不然单例就没有意义了
Singleton(const Singleton<T>&) = delete;
Singleton& operator=(const Singleton<T>& st) = delete;
//用一个智能指针来回收单例的实例,使用静态的时候就是想要使用的时候返回一个静态的实例
static std::shared_ptr<T> _instance;
//单例类析构的时候会调用成员变量也就是智能指针的析构,智能指针的析构内部会调用模版成员的析构,所以成员的析构要求公有的
public:
static std::shared_ptr<T> GetInstance() {、
//初始化的标记,不会出现竞争once_flag,然后new
static std::once_flag s_flag;
std::call_once(s_flag, [&]() {
_instance = shared_ptr<T>(new T);
});
return _instance;
}
void PrintAddress() {
std::cout << _instance.get() << endl;
}
~Singleton() {
std::cout << "this is singleton destruct" << std::endl;
}
};
template <typename T>
std::shared_ptr<T> Singleton<T>::_instance = nullptr;

本文作者:游客0721

本文链接:https://www.cnblogs.com/Gal0721/p/18150629

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   游客0721  阅读(20)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 優しい光 水谷広実
  2. 2 ひだまりの中で SONO MAKERS,鈴丸
  3. 3 白い吐息 MANYO
  4. 4 夏の子守歌 折戸伸治
優しい光 - 水谷広実
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.