LoginSignup
4
4

More than 5 years have passed since last update.

std::bind で参照を束縛する

Posted at

嵌ったのでメモ.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 が出力される
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4