1

我有两个功能

void f(const int &x) {}
void g(int& x) {}

我会做

int x = 0;
std::thread t1(f, x);

但是我不能创建std::thread t2(g, x),在这种情况下我需要 makestd::ref(x)而不是 just x,为什么有必要?

为什么可以在t1没有的情况下进行创建std::cref

4

1 回答 1

2

如果没有 .,您的f()功能将无法按预期工作std::cref()

虽然f()不打算改变 后面的值x,但这并不意味着这个引用后面的值不能在其他地方发生变异。

在本例中,没有std::cref()将原始副本int放入线程堆栈,并x引用此副本;我们看到11

另一方面, with std::cref(),x仍然引用原件;我们看到12

/**
  g++ -std=c++17 -o prog_cpp prog_cpp.cpp \
      -pedantic -Wall -Wextra -Wconversion -Wno-sign-conversion \
      -g -O0 -UNDEBUG -fsanitize=address,undefined -pthread
**/

#include <iostream>
#include <thread>

using namespace std::chrono_literals;
void
f(const int &x)
{
  std::cout << "x=" << x << '\n';
  std::this_thread::sleep_for(1000ms);
  std::cout << "x=" << x << '\n';
}

int
main()
{
  int i=1;
  // std::thread th{f, i}; // copy to thread stack
  std::thread th{f, std::cref(i)}; // reference the original i
  std::this_thread::sleep_for(500ms);
  i+=1;
  th.join();
  return 0;
}
于 2021-02-22T18:42:25.447 回答