Search code examples
c++cpuhardwareallocation

How is std::swap() implemented?


I just want to know that how is std::swap() implemented?

Does it allocate RAM for the temporary variable or simply do everything with the CPU registers?


Solution

  • That is entirely up to the compiler for the target processor. How it compiles on one machine may not be the same as the other. Some, if not most, CPUs have a XCHG instruction to swap using registers without needing a third temporary register; however, it’s up to the compiler to decide to optimize accordingly. I imagine even if not used, the compiler would still try to use registers for simple numerical or Boolean swaps when built in release mode (optimizations enabled). Even if you could coerce the compiler to use registers on one platform, there’s no reason it will obey the same on all of them. Unless you want to detect architectures and write your own assembly (a neat, but bad idea for best compatibility and support, trust me lol) I’d suggest not to micro-optimize this and just let the compiler do its thing