我正在研究 C++11 的线程特性。但以下代码在 clang (3.5) 和 gcc (4.9.2) 下均无法编译。
#include <iostream>
#include <thread>
void add(int& x) {
x += 1;
}
int main (int argc, char const *argv[])
{
int x{ 5 };
int y{ 8 };
std::thread my_thread_1{ add, x };
std::thread my_thread_2{ add, y };
my_thread_1.join();
my_thread_2.join();
std::cout << x << " " << y << std::endl;
return 0;
}
C++11 有效吗?
最佳答案
它是有效的,但是线程类复制它的参数,所以你不能直接使用引用。你必须使用 std::ref
使其工作:
std::thread my_thread_1{ add, std::ref(x) };
关于C++11 线程,它是有效代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26977946/