Warm tip: This article is reproduced from serverfault.com, please click

Passing object to a function in lambda std::thread (C++): attempt to use a deleted function

发布于 2020-11-30 15:41:18

I'm trying to do something like this:

class A {
  private:
    std::mutex my_mutex;
  public: 
    void A_function(){
        some work with the mutex;
    }
};
void B_function (A a){
     a.A_function();
}

int main () {
     A a;
     std::thread t([&a]{
          B_function(a); // error here
          });
     t.join();
}

However, I get this error:

error: attempt to use a deleted function « A »
error: attempt to use a deleted function « std::mutex::mutex(const std::mutex&) »

What am I doing wrong?

Questioner
Rey Reddington
Viewed
0
Daniel Langr 2020-11-30 23:57:01

std::mutex is not copyable, therefore, you naturally cannot copy an object of type A, which has a subobject of type std::mutex.

As a workaround, you can pass an argument to B_function by reference instead of by copy:

void B_function (A& a)
{
     a.A_function();
}

Don't know though whether it suits your needs to work with the original object instead of with its copy.