reference_wrapper in C++



std::reference_wrapper is a class template in C++ that allows you to store references to objects or functions in a way that makes them copyable and assignable. Normally, C++ references can't be stored in standard containers like std::vector or std::list, because references are not copyable. std::reference_wrapper<T> solves this problem by internally storing a pointer to the referenced object.

It acts like a wrapper around a reference and behaves almost like the original object. It can be passed to functions that take T& (a reference to T), because std::reference_wrapper<T> is implicitly convertible to T&.

This is especially useful when you want to store and work with references in STL containers or when passing around callable objects like functions or lambdas.

Example of reference_wrapper Class

In this C++ example, we demonstrate how std::reference_wrapper<int> enables storing references to variables (a, b, and c) in a std::vector. By using reference_wrapper:

#include <iostream>
#include <vector>
#include <functional>

int main() {
   int a = 10, b = 20, c = 30;
   std::vector < std::reference_wrapper < int >> refVec = {a, b, c};

   for (auto & ref: refVec) {
      // Modify original values
      ref.get() += 1;
   }

   std::cout << a << " " << b << " " << c << std::endl;
}

Following is the output of the above code ?

11 21 31

Creating Character Array Using reference_wrapper Class

Following is another C++ example, to demonstrate the use of std::reference_wrapper by creating an array of character "references" ?

#include <iostream>
#include <functional>
using namespace std;

int main() {
   char a = 't', b = 'u', c = 't', d = 'o', e = 'r', f = 'i', g = 'a', h = 'l', i = 's';

   reference_wrapper < char > ref[] = {
      a,
      b,
      c,
      d,
      e,
      f,
      g,
      h,
      i
   };

   for (char & str: ref)
      cout << str;
   return 0;
}

Following is the output ?

tutorials
Updated on: 2025-05-15T15:45:44+05:30

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy