C++核心准则CP.200:使用volatile只能表明该变量是非C++内存

时间:2022-07-22
本文章向大家介绍C++核心准则CP.200:使用volatile只能表明该变量是非C++内存,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

CP.200: Use volatile only to talk to non-C++ memory

CP.200:使用volatile只能表明该变量是非C++内存

Reason(原因)

volatile is used to refer to objects that are shared with "non-C++" code or hardware that does not follow the C++ memory model.

volatile用于表明参照的对象需要和非C++代码或硬件共享而遵守C++内存模型。

Example(示例)

const volatile long clock;

This describes a register constantly updated by a clock circuit. clock is volatile because its value will change without any action from the C++ program that uses it. For example, reading clock twice will often yield two different values, so the optimizer had better not optimize away the second read in this code:

这段代码描述一个不断被时钟电路更新的寄存器。clock被定义为volatile是因为它的值在使用它的C++程序没有任何动作的情况下被修改。例如,两次读取clock经常可以得到不同的值,因此优化器最好不要优化掉这段代码中的第二个读操作。

long t1 = clock;
// ... no use of clock here ...
long t2 = clock;

clock is const because the program should not try to write to clock.

clock定义为常量是为了表明程序不应该对clock进行写操作。

Note(注意)

Unless you are writing the lowest level code manipulating hardware directly, consider volatile an esoteric feature that is best avoided.

除非你正在编写直接操作硬件的低层次代码,否则将volatile作为冷门功能并最好避免使用。

Example(示例)

Usually C++ code receives volatile memory that is owned elsewhere (hardware or another language):

通常情况下,C++代码接受有其他某处拥有的volatile内存(硬件或其他语言):

int volatile* vi = get_hardware_memory_location();
    // note: we get a pointer to someone else's memory here
    // volatile says "treat this with extra respect"

Sometimes C++ code allocates the volatile memory and shares it with "elsewhere" (hardware or another language) by deliberately escaping a pointer:

某些C++代码会分配volatile内存并通过故意泄露指针的方式和其他部分共享(硬件或其他语言)它。

static volatile long vl;
please_use_this(&vl);   // escape a reference to this to "elsewhere" (not C++)
Example, bad(反面示例)

volatile local variables are nearly always wrong -- how can they be shared with other languages or hardware if they're ephemeral? The same applies almost as strongly to member variables, for the same reason.

volatile类型的局部变量几乎一定是错的--如果它们只能短期存在,怎么能分享给其他语言或硬件呢?由于同样的原因,该原则也几乎一定适用于成员变量。

void f()
{
    volatile int i = 0; // bad, volatile local variable
    // etc.
}

class My_type {
    volatile int i = 0; // suspicious, volatile member variable
    // etc.
};
Note(注意)

In C++, unlike in some other languages, volatile has nothing to do with synchronization.

和其他语言不同,在C++中不会为同步做任何事情。

Enforcement(实施建议)
  • Flag volatile T local and member variables; almost certainly you intended to use atomic<T> instead.
  • 标记volatile类型的局部变量和成员变量;几乎可以肯定的说你想用的其实是atomatic<T>。
  • ???

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp200-use-volatile-only-to-talk-to-non-c-memory