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

Viewed 387

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?

2 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.

The operator= has a return value for allow multiple assignments in a single line:

Object a, b;
// Short form
a = b = <value>;
// Equivalent long form
a = <value>;
b = <value>;

For accomplish this behavior, on may consider std::atomic<T>::operator= to return T, T & or std::atomic<T> &:

  • T

    This is how the operator is actually implemented.

  • T &

    Like a pointer, a reference should point to object of type T. But there is no T object stored inside an atomic object!

    So, there is nothing suitable for being returned as T &.

  • std::atomic<T> &

    With such return type one cannot write

    std::atomic<uint32_t> a, b;
    a = b = 5;
    

    b = 5 returns the type std::atomic<T> &, and one cannot assign the atomic variable a to that type because corresponded operator= is marked as deleted (assigning one atomic variable to another is prohibited).

As one can see, the only possible way for allow multiple assignments is returning T, as it is actually implemented.

Related