I’m new to c++ so sorry if obvious answer. I’m trying to get a thread to run a function from another class with an argument.
Here’s how my code is laid out:
int main(){
Engine engine;
Sounds sounds;
std::thread t(&Sounds::ManageSounds, &sounds, &engine)
/*some stuff*/
t.join();
}
class Sounds{
void ManageSounds(Engine en){
/*some stuff*/
}
}
If I run this code as is, I get this error:
error: static assertion failed: std::thread arguments must be
invocable after conversion to rvalues 129 |
typename decay<_Args>::type…>::value
If I change ManageSounds() to accept no arguments and remove the &engine in the thread, it works completely fine.
>Solution :
Your thread method ManageSounds requires an Engine parameter by value, and you pass it a pointer to Engine (&engine).
To fix it you should do one of the following:
- Pass the
engineobject iteslf (if it is copyable, and it makes sense in your case). - If you actually need pointer/reference semantics (which is quite reasonable), change the thread method accordingly. In this case you need to use
std::ref(because the ctor ofstd::threadcopies the arguments). Note: you must ensure the thread does not out-live theengineobject.
Complete code example (using copy):
#include <thread>
class Engine { /*...*/ };
class Sounds {
public:
void ManageSounds(Engine en) {
/*some stuff*/
}
};
int main() {
Engine engine;
Sounds sounds;
//--------------------------------------------vvvvvv
std::thread t(&Sounds::ManageSounds, &sounds, engine);
/*some stuff*/
t.join();
}
Complete code example (using a reference):
#include <thread>
class Engine { /*...*/ };
class Sounds {
public:
//-----------------------v
void ManageSounds(Engine & en) {
/*some stuff*/
}
};
int main() {
Engine engine;
Sounds sounds;
//--------------------------------------------vvvvvvvvvvvvvvvv
std::thread t(&Sounds::ManageSounds, &sounds, std::ref(engine));
/*some stuff*/
t.join();
}