Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ why the type of parameter of atomic_load is pointer instead of reference?

I agree the answer in When to use references vs. pointers.
But, I am wondering why C++ defines atomic_load as

template<class T>
T atomic_load(const std::atomic<T> *obj) noexcept;
                                   ^

instead of

template<class T>
T atomic_load(const std::atomic<T> &obj) noexcept;
                                   ^

Can anyone help me?

like image 256
Caesar Avatar asked Sep 19 '17 12:09

Caesar


People also ask

What is the behavior of the volatile atomic pointer function?

Otherwise the behavior is undefined. This is a generic function defined for all atomic object types A. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and volatile (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects.

What is the use of atomic<> in C++?

In C++, the std::atomic<> template class can be used to wrap many other types in order to facilitate atomic operations on that type. The template by no means guarantees any operations will actually be atomic though. If any atomic operations are not supported by the current CPU, the compiler will use mutex-based fallbacks.

What is the built-in function that implements the atomic load operation?

Built-in Function: type __atomic_load_n (type *ptr, int memorder) This built-in function implements an atomic load operation. It returns the contents of *ptr. The valid memory order variants are __ATOMIC_RELAXED, __ATOMIC_SEQ_CST, __ATOMIC_ACQUIRE, and __ATOMIC_CONSUME.

What is the generic version of the atomic load function?

Built-in Function: void __atomic_load (type *ptr, type *ret, int memorder) This is the generic version of an atomic load. It returns the contents of *ptr in *ret. Show activity on this post.


Video Answer


1 Answers

The reason why we have these free function templates at all is source compatibility with C11:

#ifdef __cplusplus
#include <atomic>
#define _Atomic(X) std::atomic<X>
#else
#include <stdatomic.h>
#endif

_Atomic(int) c;

int get_c(void) { 
    return atomic_load(&c); 
}

C doesn't have references.

If you don't need that, then c.load() or the implicit conversion to T will work just fine. Just forget that the free function ever existed.

(This is also why the memory_order version of the free function template is called atomic_load_explicit: _Generic-powered macros in C can handle varying argument types, but not varying arity.)

like image 189
T.C. Avatar answered Sep 19 '22 19:09

T.C.