c++ - General swap implementation in terms of byte swap -
the current implementation general swap in standard library like
template <class t> void swap(t& a, t& b) { t c(move(a)); = move(b); b = move(c); }
i'm wondering whether can following instead.
template <class t> void swap(t& a, t& b) { unsigned char x; auto pa = reintepret_cast<unsigned char*>(&a); auto pb = reintepret_cast<unsigned char*>(&b); auto pc = pa + sizeof(a); while (pa != pc) { x = *pa; *pa = *pb; *pb = x; ++pa, ++pb; } }
i think implementation better in terms of space usage, takes 1 byte.
there many considerations need addressed when swapping classes. pod types, swapping bytes works correctly. more complicated classes, however, may rely on invariants byte-swapping won't respect. example, consider reference member variable:
struct foo { foo() : bar{}, barref{bar} {}; int bar; int& barref; // expected refer neighboring `bar` }; int main() { foo f{}; { foo g{}; byte_swap(f, g); } // `f` invalid: `f.barref` pointing garbage }
Comments
Post a Comment