According to the clause 29.5 of Standard std::atomic is defined as struct:
namespace std {
template <class T> struct atomic { ...
I would understand if it gave direct access to data members like std::pair, but it doesn't. Or if it used like functor, std::hash for example.
What is the main reason for std::atomic being struct, not class?
This is not really a "language lawyer" question since there is no difference between struct and class in this context. You can feel assured that it makes absolutely no difference whether std::atomic<T> is a struct or a class. It is more of a "C++ history" question.
N2145 says
The proposal defines the types as POD structs and the core functions on pointers to those structs, so that types and core functions are usable from both C and C++. That is, a header included from both C and C++ can declare a variable of an atomic type and provide inline functions that operate on them. The proposal additionally provides member operators so that C++ programmers may use a more concise syntax.
Further down in the paper you can see that it seems to have been intended for implementations to be able to provide a single header that would declare member functions only in C++ mode (since structs cannot have member functions in C):
typedef struct atomic_bool
{
#ifdef __cplusplus
bool lock_free() volatile;
bool operator =( bool __v__ ) volatile;
operator bool() volatile;
bool swap( bool __v__ ) volatile;
bool compare_swap( bool * __r__, bool __v__ ) volatile;
#endif
bool __f__;
} atomic_bool;
I don't know whether implementations actually use such an approach. It is not necessary for them to do so. So it isn't necessary for C++ to define std::atomic_bool and so on as structs.
A later revision, N2393, introduced the class template std::atomic. It doesn't explain why std::atomic<T> should be a struct rather than a class; I guess it was just for consistency.
Still later came a revision that actually got accepted into C++11.
As an aside, in C++23 it will finally be possible to include the C header stdatomic.h in C++. See P0943.
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