c++ - What can go wrong implementing swap copying the bits at low level? -


consider 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 in general not safe; if std::is_trivially_copyable<t>::value true.

however cannot see how can go wrong. know real example using swap bring behavior not correct swap, , why?

suppose class contains pointer, must point 1 of own members. need copy/move semantics preserve invariant. bytewise copy ignore semantics, leaving incorrectly pointing member of different object.

for specific example, consider string "small string optimisation". contains embedded buffer use instead of dynamic memory, if string small enough; , pointer pointing either buffer, or dynamic memory. needs non-trivial copy (and move) operations make sure pointer isn't copied, rather points target object's buffer:

string(string const & other) :     size(other.size),     data(other.data == other.buffer ? buffer : new char[size]) {     copy(other.data, other.data+size, data); } 

a bytewise swap (of 2 small strings) make each string point other's buffer. you'll end dangling pointer if 1 destroyed before each other; worse, destructor implemented as

~string() {if (data != buffer) delete [] buffer;} 

will delete shouldn't, giving undefined behaviour.