#3std::reference_wrapper

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

  1. std::ref and std::reference_wrapper: common use cases
  2. P0357R3 reference_wrapper for incomplete types
  3. The C++ Standard Library, 2nd Edition, 5.4.3 Reference Wrappers

All (4 shorts)