单例
单例模式的一种实现(《Effective C++》)
class S
{
public:
static S& getInstance()
{
static S instance;
return instance;
}
private:
S() {};
S(S const&) = delete;
void operator=(S const&) = delete;
};
此处是通过C++11新的语义来保证线程的安全性,具体由编译器去处理,编译器可能使用DCLP的方式或者其他的方式完成。
The C++11 standard §6.7.4:
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
网友评论