Home > database >  std:atomic initialized with reference creates copy of underlying variable?
std:atomic initialized with reference creates copy of underlying variable?

Time:11-24

Let's consider next snippet:

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

  atomicref;
std::cout<< "atomic ref="<<atomicref.load()<<" original ref="<<ref<<" original val="<<val;

When I compile it under Mac OS X, XCode 8.3.3, c 11 I receive output like this:

atomic ref=6 original ref=5 original val=5

The line:

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

of course looks suspicious since the type under atomic is not the same as in variable's declaration - it is reference.

I wonder why the values do not match; is it correct to say that atomicref actually creates a copy of val ?

CodePudding user response:

std:atomic with reference type creates copy of underlying variable?

There is no "atomic with reference type" in your code. You merely use a reference to initialize the atomic<int> which holds an int value.

It is not specific to std::atomic and similar to

int x = 42;
int& x_ref = x;

int copy_of_x = x_ref;

copy_of_x is a copy of x not a reference.

CodePudding user response:

atomic_ref class implements atomic references in C 20. Though according to the standard, you cannot access underlying type during the lifetime of atomic_ref by any means, except by other similar atomic_ref.

So this should work:

alignas(std::atomic_ref<int>::required_alignment) int val=5;
int& ref=val;
{
   std::atomic_ref<int> atomicref(val);

     atomicref;
   std::cout<< "atomic ref="<<atomicref.load();

}
std::cout<< " original ref="<<ref<<" original val="<<val;

But normally you should just use std::atomic instead, and don't access the underlying value.

  • Related