std::ref (C++)
Why is this needed?
int yo = 5;
auto w = std::ref(yo); // w is std::reference_wrapper<int>#include <functional>
#include <iostream>
struct Counter {
int value = 0;
void inc() { ++value; }
};
int main() {
Counter c;
std::function<void()> f = std::bind(&Counter::inc, std::ref(c));
f();
f();
std::cout << c.value << "\n"; // prints 2
}
#include <thread>
#include <iostream>
#include <functional> // std::ref
void add_one(int &x) {
++x;
}
int main() {
int value = 0;
std::thread t(add_one, std::ref(value)); // pass by reference
t.join();
std::cout << value << "\n"; // prints 1
}#include <functional>
#include <iostream>
void scale(int &x, int factor) {
x *= factor;
}
int main() {
int v = 10;
auto f = std::bind(scale, std::ref(v), 3);
f(); // modifies v in place
std::cout << v << "\n"; // prints 30
}