If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. 如果当变量在初始化的时候,并发同时进入声明语句,并发线程将会阻塞等待初始化结束。
// brief: a singleton base class offering an easy way to create singleton#include<iostream>template<typenameT>classSingleton{public:static T&get_instance(){static T instance;return instance;}virtual~Singleton(){
std::cout<<“destructor called!”<<std::endl;}Singleton(const Singleton&)=delete;
Singleton&operator=(const Singleton&)=delete;protected:Singleton(){
std::cout<<“constructor called!”<<std::endl;}};/********************************************/// Example:// 1.friend class declaration is requiered!// 2.constructor should be privateclassDerivedSingle:publicSingleton<DerivedSingle>{// !!! attention!!!// needs to be friend in order to// access the private constructor/destructorfriendclassSingleton<DerivedSingle>;public:DerivedSingle(const DerivedSingle&)=delete;
DerivedSingle&operator=(const DerivedSingle&)=delete;private:DerivedSingle()=default;};intmain(int argc,char* argv[]){
DerivedSingle& instance1 =DerivedSingle::get_instance();
DerivedSingle& instance2 =DerivedSingle::get_instance();return0;}
// brief: a singleton base class offering an easy way to create singleton#include<iostream>template<typenameT>classSingleton{public:static T&get_instance()noexcept(std::is_nothrow_constructible<T>::value){static T instance{token()};return instance;}virtual~Singleton()=default;Singleton(const Singleton&)=delete;
Singleton&operator=(const Singleton&)=delete;protected:structtoken{};// helper classSingleton()noexcept=default;};/********************************************/// Example:// constructor should be public because protected token control the accessclassDerivedSingle:publicSingleton<DerivedSingle>{public:DerivedSingle(token){
std::cout<<“destructor called!”<<std::endl;}~DerivedSingle(){
std::cout<<“constructor called!”<<std::endl;}DerivedSingle(const DerivedSingle&)=delete;
DerivedSingle&operator=(const DerivedSingle&)=delete;};intmain(int argc,char* argv[]){
DerivedSingle& instance1 =DerivedSingle::get_instance();
DerivedSingle& instance2 =DerivedSingle::get_instance();return0;}