std::reference_wrapper
std::reference_wrapper<T> is a lightweight, copyable object that stores a reference to a T. It allows you to treat a reference as if it were a regular assignable object.
Key Properties
- Wraps a reference (
T&), not a pointer. - Copyable and assignable, all copies refer to the same underlying object.
- Does not extend lifetime, the referenced object must outlive the
reference_wrapper. - Access the reference with
.get()or implicit conversion toT&.
Example
#include <functional> // for std::reference_wrapper
#include <iostream>
int main()
{
int x = 42;
std::reference_wrapper<int> ref = std::ref(x);
std::cout << "Value: " << ref.get() << std::endl; // Output: Value: 42
ref.get() = 100; // Modify the original variable through the reference wrapper
std::cout << "Modified Value: " << x << std::endl; // Output: Modified Value: 100
return 0;
}