std:atomic 使用引用初始化会创建基础变量的副本吗?

Bor*_*isV 0 c++ macos std c++11 stdatomic

让我们考虑下一个片段:

int val=5;
int& ref=val;
std::atomic<int> atomicref(ref);

++atomicref;
std::cout<< "atomic ref="<<atomicref.load()<<" original ref="<<ref<<" original val="<<val;
Run Code Online (Sandbox Code Playgroud)

当我在 Mac OS X、XCode 8.3.3、c++11 下编译它时,我收到如下输出:

atomic ref=6 original ref=5 original val=5
Run Code Online (Sandbox Code Playgroud)

该行:

std::atomic<int> atomicref(ref);

当然看起来很可疑,因为原子下的类型与变量声明中的类型不同 - 它是引用。

我想知道为什么这些值不匹配;说atomicref实际上创建了val的副本是否正确?

for*_*818 6

std:atomic 具有引用类型创建基础变量的副本?

您的代码中没有“具有引用类型的原子”。您只需使用引用来初始化它atomic<int>保存的int值。

它不特定于std::atomic且类似于

int x = 42;
int& x_ref = x;

int copy_of_x = x_ref;
Run Code Online (Sandbox Code Playgroud)

copy_of_x是副本而x不是参考。