C ++ singleton -Meyers' Singleton
Simple wording
C ++ 11 previously required to double-check, but double-check unsafe so it is necessary to lock; C ++ after 11, provides local static initialization behavior in multithreaded conditions, ask the compiler to ensure that internal static variables thread security. that is local static variables are initialized at compile time, we can use this feature to complete a single case.
#include <iostream>
#include <thread>
class Singleton {
private:
Singleton() {
std::cout << "构造函数" << std::endl;
};
~Singleton() {
std::cout << "析构函数" << std::endl;
};
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
public:
static Singleton& getInstance() {
//返回local static的引用
static Singleton instance;
return instance;
}
};
int main(void)
{
for (int i = 0; i < 10; ++i) {
std::thread([]() {
std::cout << &Singleton::getInstance() << std::endl;
}).join();
}
std::cout << &Singleton::getInstance() << std::endl;
return 0;
}
Thus, even if completed singleton class, which is called Meyers' Singleton. This can in a simple manner demand, but have encountered problems where a plurality of single embodiment interdependent need a destructor sequence.
Complicated wording
Code from modern C ++ design, github address: https: //github.com/dutor/loki
Using the template parameters to set the properties of a single embodiment, it comprises a configuration policy, policy destructor, thread policy; corresponding class may also inherit their strategy to achieve
template <
typename T,
template <class> class CreationPolicy = CreateUsingNew,
template <class> class LifetimePolicy = DefaultLifetime,
template <class> class ThreadingModel = SingleThreaded >
class SingletonHolder {
public:
static T& Instance();
private:
// Helpers
static void MakeInstance();
static void C_CALLING_CONVENTION_QUALIFIER DestroySingleton();
// Protection
SingletonHolder();
// Data
typedef typename ThreadingModel<T*>::VolatileType PtrInstanceType;
static PtrInstanceType pInstance_;
static bool destroyed_;
};
This is a more complex wording, you can set the properties of a single case; Facebook with the folly of this approach, but it is, should be programmed in a simple principle, do not over optimize your program.!