Reference Wrappers

C++ takes reference functionality one step higher by introducing reference wrappers!

We'll cover the following

A reference wrapper is a copy-constructible and copy-assignable wrapper for an object of type&, which is defined in the header <functional>. It is an object that behaves like a reference, but can be copied. Contrary to classic references, std::reference_wrapper objects support two additional use cases:

  • They can be used in containers of the Standard Template Library. std::vector<std::reference_wrapper<int>> myIntRefVector
  • They can be copy instances of classes, which have std::reference_wrapper objects. That is generally not possible with references.

To access the reference of a std::reference_wrapper<int> myInt(1), the get method can be used: myInt.get(). We can also use a reference wrapper to encapsulate and invoke a callable.

Let’s discuss three different examples for a better understanding of the concept:

Get hands-on with 1200+ tech skills courses.