5

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?

Tomasz Kasperczyk
  • 1,991
  • 3
  • 22
  • 43

2 Answers2

7

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;
ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • Is there no way to pass the reference to the vector element directly? With the workaround that you proposed, I would have to rewrite a half of my project. – Tomasz Kasperczyk Feb 05 '15 at 13:46
  • 1
    @user3125731 don't use `vector`. Operator[] returns reference by copy, so, you cannot bind it to lvalue-reference. You can use move semantic probably, instead of reference. – ForEveR Feb 05 '15 at 13:51
-1

Another workaround (not tested)

#include <thread>
#include <vector>

void foo(vector& v){
  //here access v[0] and assign whatever value you'd like
  //ideally you could pass an index as well
  // if you want to access the Nth element
}

int main(){
    std::vector<bool> vec(1);
    std::thread T(foo, std::ref(vec));
}
dau_sama
  • 4,247
  • 2
  • 23
  • 30