The std::reference_wrapper
wraps a reference in a copyable, assignable object. Unlike regular references, instances
of the std::reference_wrapper
type are objects, meaning you can use them in contexts designed to pass objects by
value.
For example, you could use the std::reference_wrapper
to store references in std::vector
or std::optional
, which
don't support references directly. You could also use it to avoid copying objects of type T
when passing them to
functions that require T
to be passed by value.
The <functional>
header file, which defines the std::reference_wrapper
type, also comes with two helper
functions, std::ref
and std::cref
. They enable the creation of std::reference_wrapper
objects using argument
deduction to determine the template argument of the result.
One thing to note is that before C++ 20, the std::reference_wrapper
required the type T
to be complete. The C++ 20
standard explicitly allows for using incomplete types with the std::reference_wrapper
and the associated functions,
std::ref
and std::cref
.
Sample code
References
- std::ref and std::reference_wrapper: common use cases
- P0357R3 reference_wrapper for incomplete types
- The C++ Standard Library, 2nd Edition, 5.4.3 Reference Wrappers