11.19 Pass-by-Reference & Zero-Copy Value Exchanges
Executive Summary: Implementing generic swap templates using reference passing without heap allocations.
💻 1. Annotated Source Code
#ifndef SWAPPER_H #define SWAPPER_H template <class T> class Swapper { public: Swapper(T first, T second); void swap(); T getFirst() const; T getSecond() const; private: T first; T second; }; template <class T> Swapper<T>::Swapper(T first, T second) : first(first), second(second) {} template <class T> void Swapper<T>::swap() { T temp = first; first = second; second = temp; } template <class T> T Swapper<T>::getFirst() const { return first; } template <class T> T Swapper<T>::getSecond() const { return second; } #endif
#include <iostream> #include <string> #include "Swapper.h" using namespace std; int main() { Swapper<int> intSwapper(5, 10); Swapper<string> stringSwapper("John", "Bob"); cout << "Before swap:" << endl; cout << "\t" << intSwapper.getFirst() << ", " << intSwapper.getSecond() << endl; cout << "\t" << stringSwapper.getFirst() << ", " << stringSwapper.getSecond() << endl; intSwapper.swap(); stringSwapper.swap(); cout << "\nAfter swap:" << endl; cout << "\t" << intSwapper.getFirst() << ", " << intSwapper.getSecond() << endl; cout << "\t" << stringSwapper.getFirst() << ", " << stringSwapper.getSecond() << endl; return 0; }
📐 2. Architecture & UML Class Model
<<template class>>
Swapper<T>
Generic Swapper
Attributes / Data Members
-first : T
-second : T
Operations / Methods
+Swapper(a: const T&, b: const T&)
+swap() : void[std::swap(first, second)]
+getFirst() : T const
+getSecond() : T const
📚 3. Core C++ Concepts Deep-Dive
Generic Reference Swapping
Using template references T& allows modifying caller variables directly without copies.
⚡ 4. Embedded Systems & Hardware Reality
Register Swaps
Compilers optimize reference swaps directly into CPU register instructions (e.g. MOV/REV).
💡 5. Production-Ready Embedded Refactoring
💡 Production-Ready Refactor
template <typename T> void fastSwap(T& a, T& b) noexcept { T tmp = std::move(a); a = std::move(b); b = std::move(tmp); }
📝 Knowledge Verification Quiz
Test your understanding of the C++ concepts and embedded microcontroller trade-offs covered in this guide. Click any option for instant feedback.
Q1. Why is pass-by-reference essential in template swap functions?
Detailed Explanation:
Pass-by-reference enables in-place modification and avoids copying large payloads.