Curious
Curious

Reputation: 21510

Why is std::atomic_ref not implemented in terms of std::atomic

The referenced implementation of std::atomic_ref from the paper P0019r8 roughly keeps the template type as a member variable (https://github.com/ORNL/cpp-proposals-pub/blob/master/P0019/atomic_ref.hpp) and uses the GNU built-ins to implement atomic operations.

The question I have here is - why not reinterpret_cast to std::atomic and use the atomic operations instead? Is there a portability concern or detail I am missing?

Upvotes: 1

Views: 1298

Answers (2)

T.C.
T.C.

Reputation: 137301

There's no guarantee whatsoever that a std::atomic<T> contains nothing but a T and has the same size and alignment requirements as a T. For example, if sizeof(T) == 3, an implementation of std::atomic<T> may pad it to 4 bytes to enable the use of intrinsics. For another example, if sizeof(T) is too big for an intrinsic, std::atomic<T> might store a synchronization primitive of some sort to serialize the operation.

It follows that reinterpret_cast to std::atomic is not a viable implementation in the general case even if you ignore the general undefined behavior from the object model violations.

Upvotes: 4

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275220

Reinterpreting something to what it is not then using it is undefined behaviour.

Upvotes: 3

Related Questions