0
点赞
收藏
分享

微信扫一扫

C++核心准则CP.110:不要自已为初始化编写双重检查锁定代码


CP.110: Do not write your own double-checked locking for initialization

CP.110:不要自已为初始化编写双重检查锁定代码

 

Reason(原因)

Since C++11, static local variables are now initialized in a thread-safe way. When combined with the RAII pattern, static local variables can replace the need for writing your own double-checked locking for initialization. std::call_once can also achieve the same purpose. Use either static local variables of C++11 or std::call_once instead of writing your own double-checked locking for initialization.

从C++11开始,静态变量的初始化过程可以保证线程安全了。在和RAII模式结合使用的时候,通过使用静态局部变量,可以消除自己为初始化编写双重检查锁定代码的需求。

 

Example(示例)

Example with std::call_once.

使用std::call_once的例子。

void f()
{
static std::once_flag my_once_flag;
std::call_once(my_once_flag, []()
{
// do this only once
});
// ...
}

Example with thread-safe static local variables of C++11.

下面的代码是C++中使用线程安全的静态局部变量的示例。

void f()
{
// Assuming the compiler is compliant with C++11
static My_class my_object; // Constructor called only once
// ...
}

class My_class
{
public:
My_class()
{
// do this only once
}
};

Enforcement(实施建议)

??? Is it possible to detect the idiom?

有可能检出这种惯用法么?

 

公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

 

 

举报

相关推荐

0 条评论