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

其他-将对象传递给Lambda std :: thread(C ++)中的函数:尝试使用已删除的函数

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

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

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

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();
}

但是,我收到此错误:

错误:尝试使用删除的函数«A»
错误:尝试使用删除的函数«std :: mutex :: mutex(const std :: mutex&)»

我究竟做错了什么?

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

std::mutex是不可复制的,因此,你自然不能复制类型为的对象A,该对象具有类型为的子对象std::mutex

解决方法是,你可以通过B_function引用而不是通过副本将参数传递给

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

不知道它是否适合你使用原始对象而不是其副本的需求。