Can somebody give a simple example which demonstrates the functionality of std::ref
? I mean an example in which some other constructs (like tuples, or data type templates) are used only if it is impossible to explain std::ref
without them.
I found two questions about std::ref
here and here. But in the first one it goes about a bug in a compiler and in the second one, examples of use of std::ref
do not contain std::ref
and they involve tuples and data type templates which make understanding of these examples complex.
You should think of using std::ref
when a function:
std::bind
or the constructor for std::thread
.std::ref
creates a copyable value type that behaves like a reference.
This example makes demonstrable use of std::ref
.
#include <iostream> #include <functional> #include <thread> void increment( int &x ) { ++x; } int main() { int i = 0; // Here, we bind increment to a COPY of i... std::bind( increment, i ) (); // ^^ (...and invoke the resulting function object) // i is still 0, because the copy was incremented. std::cout << i << std::endl; // Now, we bind increment to std::ref(i) std::bind( increment, std::ref(i) ) (); // i has now been incremented. std::cout << i << std::endl; // The same applies for std::thread std::thread( increment, std::ref(i) ).join(); std::cout << i << std::endl; }
Output:
0 1 2
void PrintNumber(int i) {...} int n = 4; std::function<void()> print1 = std::bind(&PrintNumber, n); std::function<void()> print2 = std::bind(&PrintNumber, std::ref(n)); n = 5; print1(); //prints 4 print2(); //prints 5
std::ref
is mainly used to encapsulate references when using std::bind
(but other uses are possible of course).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With