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?
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With