I spend an hour wiggling down a large class I needed to pass a member function of to a minimal example. The compiler error given is:
error C2664: 'B::B(const B &)': cannot convert argument 1 from '_Ty' to 'const B &'
Below is a minimal example and the Code compiles fine when using a pointer to the mutex. Can somebody help me understand what went wrong here and why and how I could have gotten hints towards that from the error message in 'tuple'?
Thanks everyone!
#include <functional>
#include <iostream>
#include <string>
#include <mutex>
class A {
public:
std::string Init(std::function<std::string(void)> f) {
return f();
}
};
class B {
std::mutex lock;
std::string member = "Hello World!";
public:
std::string foo() {
return member;
}
};
int main() {
auto callback3 = std::bind(&B::foo, B());
auto instance = A();
std::cout << instance.Init(callback3) << "\n";
}
CodePudding user response:
A std::mutex
is non-copyable, its copy constructor is deleted. There are no defined semantics for copying a mutex, what does that mean? If a mutex has locked something, does it mean that, somehow, two mutexes managed to lock the same object, the original and the copy, and both must be unlocked. For this reason a std::mutex
is not copyable.
This makes B
non-copyable too.
std::bind
requires a copyable callable object to work with, which results in this compilation error.