CppDemo1/dl.h

130 lines
3.0 KiB
C++
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// Created by 张衡 on 25-6-26.
//
#ifndef DL_H
#define DL_H
#include <iostream>
#include <mutex>
#include <memory>
// class Single2 {
// private:
// Single2() {
// };
//
// Single2(const Single2 &) = delete;
//
// Single2 &operator=(const Single2 &) = delete;
//
// public:
// ~Single2() {
// std::cout << "~Single2()" << std::endl;
// }
//
// static Single2 &GetInstance() {
// // 线程安全
// static Single2 single;
// return single;
// }
// };
//
// class SingleOnceFlag {
// public:
// ~SingleOnceFlag() { std::cout << "~SingleOnceFlag()" << std::endl; }
//
//
// static std::shared_ptr<SingleOnceFlag> GetInst() {
// // 复用
// static std::once_flag once_flag;
// // 一个量表示有无被call_once初始化
// std::call_once(once_flag, []() {
// //初始化单例
// _instance = std::shared_ptr<SingleOnceFlag>(new SingleOnceFlag());
// std::cout << "SingleOnceFlag()" << std::endl;
// });
// return _instance;
// }
//
// private:
// static std::shared_ptr<SingleOnceFlag> _instance;
//
// SingleOnceFlag() = default;
//
// SingleOnceFlag(const SingleOnceFlag &) = delete;
//
// SingleOnceFlag &operator=(const SingleOnceFlag &) = delete;
// };
// class SingleNet;
// class SafeDeletor
// {
// public:
// void operator()(SingleNet *sf)
// {
// std::cout << "this is safe deleter operator()" << std::endl;
// delete sf;
// }
// };
//
// class SingleNet{
// public:
// static std::shared_ptr<SingleNet> getInstance(){
// static std::once_flag flag;
// std::call_once(flag, []{
// _instance = std::shared_ptr<SingleNet>(new SingleNet(), SafeDeletor());
// });
// return _instance;
// }
//
// void PrintAddress() {
// std::cout << _instance << std::endl;
// }
// //定义友元类,通过友元类调用该类析构函数
// friend class SafeDeletor;
// private:
// SingleNet() = default;
// SingleNet(const SingleNet&) = delete;
// SingleNet& operator=(const SingleNet& st) = delete;
// ~SingleNet() {
// std::cout << "this is singleton destruct" << std::endl;
// }
// static std::shared_ptr<SingleNet> _instance;
//
// };
template <typename T>
class Singleton {
protected:
Singleton() = default;
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
static std::shared_ptr<T> _instance;
public:
~Singleton() = default;
static std::shared_ptr<T> GetInst() {
static std::once_flag flag;
std::call_once(flag, [](){
_instance = std::shared_ptr<T>(new T());
});
return _instance;
}
};
template <typename T>
std::shared_ptr<T> Singleton<T>::_instance = nullptr;
class SingleNet : public Singleton<SingleNet> {
friend class Singleton<SingleNet>;
private:
SingleNet() = default;
public:
~SingleNet() {
std::cout << "~SingleNet" << std::endl;
}
};
#endif // DL_H