嵌ったのでメモ.std::bindで何も考えずに参照を引数に取る関数を束縛すると値渡しになってしまう.
#include <iostream>
#include <functional>
void f(int& x) { x = 42; } // 参照を引数に取る
int main() {
int x = 0;
auto g = std::bind(f, x);
g(); // ここで x = 42 となって欲しい
std::cout << x << std::endl; // 0 が出力される
}
std::ref を使うと上手く動く.
#include <iostream>
#include <functional>
void f(int& x) { x = 42; }
int main() {
int x = 0;
auto g = std::bind(f, std::ref(x));
g();
std::cout << x << std::endl; // 42 が出力される
}