educative.io

Reference_wrapper

I am not clear on why using reference_wrapper. In which scenario, do we really have to use this wrapper? The example given in this Introduction to Reference_Wrapper did not clearly explain why we need to put the whole foo function inside the reference_wrapper. How does this give benefits over normally calling the foo function without the wrappers? Thank you!

Hi @Chau_Nguyen
Reference wrappers have the following use cases:

  • It can be used to store references in standard containers and to pass objects by reference to std::bind (binds one or more arguments to a function object).
  • It is frequently used as a mechanism to store references inside standard containers like std::vector which cannot normally hold references.

Normal calling with pointers has to be dereferenced to obtain the value of the object they refer to. While reference_wrappers have an implicit conversion operator and can be called like the object they wrap. In the given example reference_wrappers is used just to introduce this concept and obviously has the above-mentioned benefits as well.

Hope it will help , Thank you :blush: