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

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -