New adopted paper: N3668, exchange() Utility Function, revision 3 -- Jeffrey Yasskin

Note: This paper was adopted into draft C++14 on Saturday at the Bristol UK ISO C++ meeting.

A new WG21 paper is available. A copy is linked below, and the paper will also appear in the next normal WG21 mailing. If you are not a committee member, please use the comments section below or the std-proposals forum for public discussion.

Document number: N3668

Date: 2013-04-19

exchange() utility function, revision 3

by Jeffrey Yasskin

Excerpt:

Atomic objects provide an atomic_exchange function ([atomics.types.operations.req]p18) that assigns a new value to the object and returns the old value. This operation is also useful on non-atomic objects, and this paper proposes adding it to the library. The benefit isn't huge, but neither is the specification cost.

template<typename T, typename U=T>
T exchange(T& obj, U&& new_val) {
  T old_val = std::move(obj);
  obj = std::forward<U>(new_val);
  return old_val;
}

For primitive types, this is equivalent to the obvious implementation, while for more complex types, this definition

  • Avoids copying the old value when that type defines a move constructor
  • Accepts any type as the new value, taking advantage of any converting assignment operator
  • Avoids copying the new value if it's a temporary or moved.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.