I'm trying to understand the conditions on std::swap
from [C++11: utility.swap]. The template is defined as
template <typename T> void swap(T &, T &)
(plus some noexcept
details) and as having the effect of "exchanging the values stored at the two locations".
Is the following program have well-defined?
#include <utility>
int main()
{
int m, n;
std::swap(m, n);
}
If I wrote swap code myself (i.e. int tmp = m; m = n; n = tmp;
), it would have undefined behaviour, since it would attempt lvalue-to-rvalue conversion on an uninitialized object. But the standard std::swap
function does not seem to come with any conditions imposed on it, nor can one derive from the specification that there is any lvalue-to-rvalue and thus UB.
Does the standard require std::swap
to perform some magic that is well-defined on uninitialized objects?
To clarify the point, consider the function void f(int & n) { n = 25; }
, which never has undefined behaviour (since it does not read from n
).