将向量元素的引用传递给线程函数

Tom*_*zyk 5 c++ multithreading reference vector c++11

我正在尝试做这样的事情:

#include <thread>
#include <vector>

void foo(bool &check){

}

int main(){
    std::vector<bool> vec(1);
    std::thread T(foo, std::ref(vec[0]));
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,gcc抛出一个错误:

prog.cpp: In function 'int main()':
prog.cpp:10:34: error: use of deleted function 'void std::ref(const _Tp&&) [with _Tp = std::_Bit_reference]'
  std::thread(foo, std::ref(vec[1]))
                                  ^
In file included from /usr/include/c++/4.9/thread:39:0,
                 from prog.cpp:1:
/usr/include/c++/4.9/functional:453:10: note: declared here
     void ref(const _Tp&&) = delete;
Run Code Online (Sandbox Code Playgroud)

但它适用于普通变量:

bool var;
std::thread(foo, std::ref(var));
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我不能传递对vec元素的引用.有人可以解释原因吗?有没有解决方法?

For*_*veR 6

问题是,你使用std::vector<bool>.operator []vector<bool>回报不BOOL,但是std::vector<bool>::reference,这是代理类.您可以使用以下内容:

bool value = vec[0];
std::thread T(foo, std::ref(value));
T.join();
vec[0] = value;
Run Code Online (Sandbox Code Playgroud)