Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::swap atomic in C++0x due to rvalue references?

Tags:

c++

c++11

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?

like image 316
ronag Avatar asked Aug 10 '10 07:08

ronag


3 Answers

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.

like image 90
wilx Avatar answered Nov 14 '22 12:11

wilx


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.

like image 42
David Rodríguez - dribeas Avatar answered Nov 14 '22 11:11

David Rodríguez - dribeas


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.

like image 1
Motti Avatar answered Nov 14 '22 11:11

Motti