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

新书介绍

以下是本人3月份出版的新书,拜托多多关注!

 

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

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

 


 

觉得本文有帮助?请分享给更多人。

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

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

 

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

 

你可能感兴趣的:(C++,C++,核心准则,初始化,双重,锁)