Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::atomic<T>::operator= should return a value instead of reference?

When using atomic type in c++

Why does std::atomic<T>::operator= should return a value instead of reference? It's not like other common assignment operator which returns a reference.

From a cppreference site I can get some hint.

Unlike most assignment operators, the assignment operators for atomic types do not return a reference to their left-hand arguments. They return a copy of the stored value instead.

I can guess that if I use reference, it has a problem of atomic things. But I'm not completely clear.

Do you have any example for the async error case ?

And if I return a value instead of a reference, why does the async error gone?

like image 441
myoldgrandpa Avatar asked May 05 '26 22:05

myoldgrandpa


1 Answers

Do you have any example for the async error case ?

The return type of that operator is T. If it were T&, you could do something like:

atomic<int> i;
++(i = 10);

And the ++ would be a non-atomic read-increment-write, which is very wrong.

And if I return a value instead of a reference, why does the async error gone?

Since it returns a copy, not a reference, you can't do what I showed above.

like image 82
Ayxan Haqverdili Avatar answered May 08 '26 11:05

Ayxan Haqverdili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!