+ 3

Someone explain about reference_wrapper in c++

I know a little about reference_wrapper in c++. I searched the internet and sololearn forum, but couldn't find a good explanation of it. Explain how it works, not just how to use it. Thank you ^^

21st Jul 2021, 3:06 AM
Rishi
Rishi - avatar
4 Respuestas
+ 6
If you look at the description of std::reference_wrapper, https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper the main usage of it is " as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references...". Sure enough, standard containers including std::vector cannot hold references. If you do something like std::vector<int&> vec; , the compiler complains. An explanation of why this is not allowed can be found here: https://stackoverflow.com/questions/922360/why-cant-i-make-a-vector-of-references For whatever reason if you need to store references in there, std::reference_wrapper can help construct such an object type compatible with standard containers. See: https://code.sololearn.com/cm8tyNEq2usa/?ref=app
21st Jul 2021, 3:53 AM
Hatsy Rei
Hatsy Rei - avatar
+ 10
std::reference_wapper::get is documented here: http://www.cplusplus.com/reference/functional/reference_wrapper/get/ Basically, it returns the referred element, which allows you to assign values to it. In most circumstances (including std::cout) you would want to use it, since trying to print the reference_wrapper object itself depends on whether the type of the referred element has a non-templated operator<<. https://stackoverflow.com/questions/34144326/why-reference-wrapper-behaves-differently-for-built-in-types This is an example where std::cout fails for std::reference_wrapper<std::string>, but works when using the .get method which returns the actual string variable.
22nd Jul 2021, 2:29 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Thank you! I got it, wish you a happy day ahead ^-^
22nd Jul 2021, 5:05 AM
Rishi
Rishi - avatar
+ 1
Hmm... I think I get it, but I have one doubt. When I use this line (in the code you attached), "std::cout<<obj[0];", it prints 39(correct output) But when I use "std::cout<<obj[0].get();', it still prints 39(correct output). So what's happening here? For assigning a new value to a reference, I have to use get() method, else it won't work. But how get() method does nothing in std::cout'ing it?
22nd Jul 2021, 1:53 AM
Rishi
Rishi - avatar