C++ 11 Threads,它是有效的代码吗?

Ins*_*oop 0 c++ multithreading c++11

我正在玩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;
}
Run Code Online (Sandbox Code Playgroud)

它是有效的C++ 11吗?

Som*_*ude 7

它是有效的,但线程类复制其参数,因此您不能直接使用引用.你必须使用std::ref它来使它工作:

std::thread my_thread_1{ add, std::ref(x) };
Run Code Online (Sandbox Code Playgroud)

  • @InsideLoop使用`std :: cref`进行const引用,否则将复制arg.(除非编译器以某种方式能够优化出来,我猜) (2认同)