单例模式
留神:单例模式会让程序变得难以测试,所以尽可能不要应用单实例模式。
保障一个类只有一个实例,并且提供了拜访该实例的全局拜访点。
线程平安的单例模式 -C++11
Singleton.h
#pragma once
template<typename T>
class Singleton
{
public:
static T& instance() {static T instance{ token{} };
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator= (const Singleton) = delete;
protected:
struct token {};
Singleton() {}
};
Example
#include <Singleton.h>
#include <iostream>
class Test final : public Singleton<Test>
{
public:
Test(token) {std::cout << "constructed" << std::endl;}
~Test() { std::cout << "destructed" << std::endl;}
void use() const { std::cout << "in use" << std::endl;};
};
int main()
{
// Test cannot_create; /* ERROR */
std::cout << "Entering main()" << std::endl;
{auto const& t = Test::instance();
t.use();}
{auto const& t = Test::instance();
t.use();}
std::cout << "Leaving main()" << std::endl;}
隐患
如果单例类位于 dll
库中,是否还能保障惟一?
参考文献
1.https://codereview.stackexcha…
2.https://stackoverflow.com/que…
3.https://gameprogrammingpatter…
4.https://gpp.tkchu.me/singleto…
更新地址
C++11 单例模式(线程平安)