mercredi 24 novembre 2021

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

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 ?

Aucun commentaire:

Enregistrer un commentaire