MeyersSingleton
应用场景:配置管理,日志记录,线程池,连接池,内存池,对象池,消息队列。
一言以蔽之:程序在运行期间对全局且唯一的资源的一种统一的访问方式就是单例。
#include <bits/stdc++.h>
class MeyersSingleton {
private:
MeyersSingleton() = default;
~MeyersSingleton() = default;
MeyersSingleton(const MeyersSingleton&) = delete;
MeyersSingleton& operator=(const MeyersSingleton&) = delete;
std::mutex mtx_;
public:
static MeyersSingleton& getInstance() {
static MeyersSingleton instance;
return instance;
}
void logError(const std::string& message) {
std::lock_guard<std::mutex> guard(mtx_);
std::cerr << message << '\n';
}
};
int main() {
MeyersSingleton::getInstance().logError("hhh");
return 0;
}
#include <bits/stdc++.h>
class MeyersSingleton {
template<class T>
friend T& singleton();
private:
MeyersSingleton() = default;
~MeyersSingleton() = default;
MeyersSingleton(const MeyersSingleton&) = delete;
MeyersSingleton& operator=(const MeyersSingleton&) = delete;
std::mutex m_lock;
public:
void logError(const std::string& message) {
std::lock_guard<std::mutex> guard(m_lock);
std::cerr << message << '\n';
}
};
template<class T>
T& singleton() {
static T instance;
return instance;
}
int main() {
singleton<MeyersSingleton>().logError("hhh");
return 0;
}