jeudi 5 février 2015

Passing a reference of a vector element to a threaded function

I'm trying to do something like this:



#include <thread>
#include <vector>

void foo(bool &check){

}

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


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;


However it works with a normal variable:



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


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


Aucun commentaire:

Enregistrer un commentaire