Here's how I do it:
//untested code template<typename T> T compare_and_swap(atomic<T>& reg,T newVal ) { oldVal = atomic_load(reg); while(!atomic_compare_exchange_weak(®, &oldVal, newVal)); return oldVal; }
The exchange comparison function will update the oldval value if it is not executed. Therefore, there is no need to repeat this.
As you can see, I prefer to use explicit atomic operations. This is due to the fact that they are not always implemented. As explained by Herb Sutter here (the rest of the video may also interest you :)).
As an unnecessarily superfluous thought, I would like to warn against using this function with the help of types trivially copied . Or "normal" pointers. General pointers are generally ok :).
source share