Consider this code:
#include <cstring>
#include <memory>
namespace mstd {
template <typename T>
void swap(T& lhs, T& rhs) {
char tmp[sizeof(T)];
std::memcpy(tmp, std::addressof(lhs), sizeof(T));
std::memcpy(std::addressof(lhs), std::addressof(rhs), sizeof(T));
std::memcpy(std::addressof(rhs), tmp, sizeof(T));
}
}
Using mstd::swap
is in general not safe; it is only if std::is_trivially_copyable<T>::value
is true.
However I cannot see how it can go wrong. Do anyone know a real example where using this swap will bring a behavior that is not a correct swap, and why?