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

时间:2022-07-22
本文章向大家介绍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?

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

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp110-do-not-write-your-own-double-checked-locking-for-initialization