1

I've noticed the implementation of std::reference_wrapper in C++11, however, I'm wondering why I should use the std::reference_wrapper instead of a "raw" reference variable.

I've understood that a reference wrapper is an object that can be copied and whatever, but still, why should I use it instead of a reference? What's the point of this feature? Let's consider the following pseudo-code

class A;

A myA{}; 
A& refMyA = &a;
std::reference_wrapper<A> refWMyA = std::ref(A); 

void foo (const A& aRef) {// do stuff}

void bar (const std::reference_wrapper<A> aRef) {// do stuff}

Why should I prefer bar rather than foo?

Evethir
  • 31
  • 3
  • You probably never need to use `std::reference_wrapper` directly, it's just the return type of `std::ref` which allows passing references through templated code which stores values by copying, e.g `std:: bind` – Alan Birtles Jul 13 '20 at 07:14

0 Answers0