Since we have rvalue references in C++0x it seems to me that it should be possible to implement std::swap as an atomic operation with CAS. Is this the case in the new standard, and if not why?
It is not atomic. Atomic operations are not cheap and 99% of the time you do not need the atomicity. There are (IIRC) some other means to get atomic operations but std::swap()
is not one of them.
Simple answer no, not really.
While you can use CAS to implement atomic operations, in most cases you would have to redesign part of the implementation to do so, and you will, in most cases, have an impact in performance in all usages.
Consider a current implementation of a vector in g++. It keeps three pointers: begin
, end
, end_of_capacity
. How would you make swap
atomic for such a vector? You could simplify things by pushing all three pointers into a dynamically allocated block of memory, and then implementing an atomic swap
would be simpler, just swap the pointers. The problem is that you have added an extra memory allocation to the container and an extra dereference operation in each and every access through the container (iterators would perform similar to the original implementation).
Do read at this answer by FredOverflow for a simple explanation on move semantics.
Not every class can have a move assignment operator which can be implemented more efficiently than the regular assignment operator. Case in point std::array
which has a native array as a member. Another case is a std::string
where the small string optimization is used (for small strings).
Therefore generally you can't say anything about std::swap
with move semantics that you couldn't say about std::swap
in C++98. For some cases it will be better but not for the general case.
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