将向量元素的引用传递到线程函数 [英] Passing a reference of a vector element to a threaded function

查看:237
本文介绍了将向量元素的引用传递到线程函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

#include <thread>
#include <vector>

void foo(bool &check){

}

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

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

Unfortunately gcc throws an error:

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;

但是它使用正常变量:

bool var;
std::thread(foo, std::ref(var));

我不知道为什么我不能传递vec元素的引用。有人可以解释为什么吗?是否有解决方法?

I have no idea why I can't pass a reference to the vec element. Can someone explain why? Is there any workaround?

推荐答案

问题是,您使用 std :: vector< bool> 运算符[] 向量< bool> 不返回bool, std :: vector< bool> :: reference ,即代理类。
您可以使用类似:

Problem is, that you use std::vector<bool>. operator [] for vector<bool> returns not bool, but std::vector<bool>::reference, that is proxy class. You can use something like:

bool value = vec[0];
std::thread T(foo, std::ref(value));
T.join();
vec[0] = value;

这篇关于将向量元素的引用传递到线程函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆