Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::ref

Use case

Pass references to threads (which copy arguments by default).

Explanation

std::thread copies its arguments by default. std::ref(x) creates a wrapper object that holds a pointer.

Code

#include <functional>
#include <iostream>
#include <thread>

void analyze(int &counter) { counter++; }

int main() {
  int count = 0;
  std::thread t(analyze, std::ref(count));
  t.join();

  std::cout << "Count: " << count << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/std-ref
Count: 1