Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std::atomic defined as struct?

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?

like image 653
αλεχολυτ Avatar asked Nov 25 '25 02:11

αλεχολυτ


1 Answers

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.

like image 120
Brian Bi Avatar answered Nov 28 '25 17:11

Brian Bi