6

The C++ Standard Library has both free functions and member functions for atomic compare and swap operations.

As noted for free functions:

These functions are defined in terms of member functions of std::atomic:

  1. obj->compare_exchange_weak(*expected, desired)
  2. obj->compare_exchange_strong(*expected, desired)
  3. obj->compare_exchange_weak(*expected, desired, succ, fail)
  4. obj->compare_exchange_strong(*expected, desired, succ, fail)

What is the reason for having free functions? Wouldn't it be enough to have member functions only? Don't they do the same thing?

Community
  • 1
  • 1
ks1322
  • 33,961
  • 14
  • 109
  • 164
  • In general; member functions are provided when they can do a better (faster) job than the more generic free functions. – Jesper Juhl Jan 21 '18 at 16:13

1 Answers1

6

Consistency with the C stdatomic.h operations.

If you use the free functions, the same atomics-manipulating code will work in both C and C++, with only a typedef needing to be conditionally defined.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 1
    So then I guess the reverse question is why do we need the member functions at all, if the free functions already serve the same purpose? – Silvio Mayolo Jan 21 '18 at 15:54
  • 1
    @SilvioMayolo: The member functions (which also use reference types) permit writing new C++-only code in an object-oriented style. C++ is a multi-paradigm language, so you'll often find multiple ways of doing the same thing (e.g. `std::for_each` vs ranged-for). Not because more than one is needed, but because more than one is convenient. And by defining one in terms of the other, it means that you only have to understand it once. – Ben Voigt Jan 21 '18 at 15:59
  • @Ben Voigt comparing range-for and `std::for_each` like that is not really fair. They are *not* the same thing. True, if you want to apply an operation to a whole container they do the (semantically) same thing. But if you want to apply an operation to a *sub-range* of a container then range-for won't hack it but `std::for_each` is just what you need. – Jesper Juhl Jan 21 '18 at 16:23
  • @JesperJuhl: ranged-for supports range objects just fine – Ben Voigt Jan 21 '18 at 17:37