Is std::swap(x, x) guaranteed to leave x unchanged?

I believe this may be covered, at least in C++20(a), by the [utility.requirements] section which states:

15.5.3.2 describes the requirements on swappable types and swappable expressions.

That referenced section, [swappable.requirements], further states (my emphasis in the final two bullet points):

An object t is swappable with an object u if and only if:

  • the expressions swap(t, u) and swap(u, t) are valid when evaluated in the context described below; and
  • these expressions have the following effects:
    • the object referred to by t has the value originally held by u; and
    • the object referred to by u has the value originally held by t.

It seems to me that, if self-swap somehow damaged the contents, those bolded sections would be invalidated, meaning that they wouldn’t be swappable.

That same section also later states:

An rvalue or lvalue t is swappable if and only if t is swappable with any rvalue or lvalue, respectively, of type T.

There’s no waffling around with self-swaps there, it clearly states any rvalue or lvalue (respectively), including itself.


(a) Both these constraints also exist in C++17, c++14, and C++11, anything older than that, I don’t really care about 🙂

Leave a Comment