2

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?

JeJo
  • 30,635
  • 6
  • 49
  • 88
Jhon Viks
  • 23
  • 5
  • 1
    Every compiler is free to implement it the way they want to but Stroustrup suggests something that might be followed by compiler writers. See http://www.stroustrup.com/C++11FAQ.html#rval. – R Sahu Apr 18 '19 at 04:22
  • The standard library is (largely) a header-only library. So, if you really want to know how `std::swap()` is implemented, simply open your compiler's `` and/or `` header file and look for yourself. – Remy Lebeau Apr 18 '19 at 06:09

1 Answers1

0

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

Shahzaib Mazari
  • 434
  • 4
  • 14