gpt4 book ai didi

c++ - volatile 复制构造函数有什么用?

转载 作者:可可西里 更新时间:2023-11-01 16:38:13 25 4
gpt4 key购买 nike

您能举一个简单的或真实的例子来演示 volatile 复制构造函数的用法吗?

我只是想不出一个。

最佳答案

正如@Nawaz 已经指出的那样:

When you have volatile objects, you need volatile copy-ctor. So the question boils down to this: when do you need volatile objects?

使用 volatile 关键字的主要原因通常是禁用优化。那就是如果你有这样的东西:

bool flag = false;
if(!flag) {}

编译器会发现标志无法更改,因此无需每次都检查标志 - 所以不会。但是,如果您将标志变量设置为易变的 - 它会。

这里是volatile关键字原始使用的意见:link

简而言之,它最初是用来通过MMIO访问硬件的,这可能有点不寻常:

unsigned char* pControl = 0xff24 ;
*pControl = 0 ;
*pControl = 0 ;
*pControl = 0 ;

并且您不希望这 3 个分配因优化而成为一个。

这是 Andrei Alexandrescu 关于多线程软件中的 volatile 的论文:link

有一些论文批评 Alexandrescu 的论文,但我找不到。关键在于他正在丢弃不稳定的属性(property)等等。

注意@JanHudec 指出的关于多线程的非常重要的事情:

volatile is totally useless for multi-threaded context, because while it prevents optimization, it does not generate explicit barriers. And without those write done on one CPU may not become visible to another CPU (architecture dependent; x86 has coherent caches, so writes are always visible there).

Also volatile does not force the operation to be atomic. On x86 assignment is always atomic, but it's not the case with all CPU architectures. And more complex operations like increment can only be made atomic using std::atomic.

关于c++ - volatile 复制构造函数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19264080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com