Thread in C++11 not in class member [duplicate] - c++

This question already has answers here:
Start thread with member function
(5 answers)
Closed 5 years ago.
I'm recently using C++11 threads and I have a question about something (strange for me) happened.
I created a method inside a class, able to start thread. The starting thread method and the callback function of the thread are class methods.
To clarify, in my Person.cpp file I have:
void Person::callbackForThread(){
...
}
void Person::startThread(){
this call threads. Something like:
thread(callbackForThread);
}
The problem is that C++11 doesn't allow me to declare these two function as class methods. This means that if I declare them as normal function, i.e:
void callbackForThread(){
...
}
void startThread(){
this call threads. Something like:
thread(callbackForThread);
}
Everythings works. I would know how could I declare thread and callback inside a class in C++, if it is possible.
For the farther, I have omitted the inclusion of the libraries and the name of the real class. The class shown in this question is fictitious.

This is because Person::callbackForThread takes an hidden first argument: this.
This is where lambdas and std::bind come in handy:
thread([this]() { this->callbackForThread(); });
or
using namespace std::placeholders;
thread(std::bind(&Person::callbackForThread, this, _1));
From krzaq feedback: if thread is std::thread, it needs to be detached or saved somehow.

Related

How to make a callback in C++: use a class member function as a parameter [duplicate]

This question already has answers here:
Callback functions in C++
(11 answers)
Closed 2 years ago.
I started using C++ recently and at one point I needed to set up a callback, i.e. call a function of another class and pass to it as a parameter the name of one of my own functions so that it calls it back. At first I tried this:
void myOtherFunction(void (*oneOfMyFunctions)(void)) {
oneOfMyFunctions();
}
Unfortunately this code doesn't support class member functions because it is (correct me if I am wrong) ...C code.
This can work.
void myOtherFunction(void (*oneOfMyFunctions)(void)) {
oneOfMyFunctions();
}
However, your problem may be due to trying to pass member functions into this function. If member_function is a member function of class A, the expression &member_function inside class A has a type of void (A::*)(void), not void (*)(void) like you want (that is, it wants an A pointer in addition to its normal parameters). You can use std::bind():
std::bind(&member_function, this)
to create a function object which can be called with an empty parameter list. However, then you would need to change your member function signature to something like this:
template <typename FuncType>
void myOtherFunction(FuncType oneOfMyFunctions) {
oneOfMyFunctions();
}
or, like Th0rgal may have said,
void myOtherFunction(std::function<void()> oneOfMyFunctions) {
oneOfMyFunctions();
}
Here is a working way to do that:
void myOtherFunction(std::function<void()> oneOfMyFunctions) {
oneOfMyFunctions();
}
And inside my class:
myOtherFunction([&] {
oneOfMyFunctions();
});
Some explanations:
In std::function<void()>, void is what is returned by the function and () contains the types of its parameters (mine is empty because it doesn't have any).
In the 2nd code I am using a lambda to keep the context, as a bind would do (but lambdas replace them).

Why overload the () operator (callable operator) in a C++ class or struct when you could use a constructor? [duplicate]

This question already has answers here:
Why use functors over functions?
(7 answers)
Closed 3 years ago.
Why would you overload the () operator in a C++ class or struct in C++11 or higher? As far as I can tell, these operators are overloaded when you want to pass objects like classes or structs into a std::thread and kick off a new thread with a package of data to go along with it, through a callable type.
But other than that, why else would you overload the () operator? Couldn't you simply do the same things in the constructor for a class or struct?
Why use
struct MyCallableStruct{
void operator() () {
dosomething();
}
}
when you could do
struct MyCallableStruct{
MyCallableStruct() { dosomething(); }
}
They're totally different.
First and most importantly, When you use operator(), it can be passed as function parameters (by object).
In contrast, when implemented by constructor, it can only be passed through templates (by class)
Second, operator() can be called several times after object created,
while construtor can only be called at constructing
All in all, they're different and useful in different scenarios

How can I create C++ functions which return each other? [duplicate]

This question already has answers here:
Recursive typedef function definition : std::function returning its own type
(3 answers)
Closed 7 years ago.
I want to have a few functions in C++ where each function represents a screen in the program. The functions handle user interaction, and based on that will return a std::function to one of the other functions, with parameters bound via std::bind so that the return value can be called with no arguments. It is possible to get from any function to any other function by this process, without using recursion - the main function would be an infinite loop that just calls the returned function over and over.
But I'm stumped here - what should the definition of the return type be for these functions? They need to return std::function objects that take no parameters, but that's as far as I can get. std::function<what_goes_here ()>?
C++ doesn't have any function type that directly or indirectly includes itself. You need some way to avoid the recursion in the type definition.
One way of doing that is by not returning a function. Instead, return a struct containing a function. Self-contained example with function pointers:
struct wrapper { wrapper (*function)(); };
wrapper f1();
wrapper f2();
wrapper f1() { return {f2}; }
The same approach also works with std::function.

Thread constructor syntax - passing class members by reference [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Start thread with member function
I have recently been playing around with the new std::thread library in c++11 and I came across a problem. When i try to pass a classes function into a new thread, it gives me an error (I dont have the exact error text right now since im away from home)
I had a class like this
class A
{
void FunctA();
void FunctB();
void run()
{
std::thread t(FunctA);
std::thread r(FunctB);
}
}
What am I doing wrong?
class A
{
void FunctA();
void FunctB();
void run()
{
std::thread t(&A::FunctA, this);
std::thread r(&A::FunctB, this);
}
};
Pointers to member functions are different from pointers to functions, syntax of calling them is different, as well, and requires instance of class. You can just pass pointer to instance as second argument of std::thread constructor.
I think, the problem is that you can't get pointer to member function in a way similar to functions. Here you will find more information about this.
Also, it would be much easier to answer, if you provided compipler error text.

How do I pass an instance member function as callback to std::thread [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Start thread with member function
I'm VERY new to C++. My experience has mostly been with javascript and java.
I'm using Xcode on Lion. The following code gives me a compilation error "Reference to non-static member function must be called; did you mean to call it with no arguments?"
class MyClass {
private:
void handler() {
}
public:
void handleThings() {
std::thread myThread(handler);
}
};
I also tried this->handler, &handler, and other variations, but none of them worked. This code compiles though and accomplishes what I want it to:
class MyClass {
private:
void handler() {
}
public:
void handleThings() {
std::thread myThread([this]() {
handler();
});
}
};
Why can't I pass a reference to a member function? Is my work-around the best solution?
std::thread myThread(&MyClass::handler, this);
myThread.join();
Use lambda to access class members within a member function, you need to capture this. [this] is mandatory in below code:
void handleThings()
{
std::thread myThread([this]() {
handler();
});
}
You could capture this by reference but it's not as efficient as capturing it by value. because going through the reference requires double indirection (modulo compiler optimizations)
void handleThings() {
std::thread myThread([&]() {
handler();
});
}
Lambdas are usually a better choice than bind.
Easier for readers to understand.
More efficient.
You can use std::mem_fun, if you dont want to use a lamda.
Are you able to do this?
std::thread myThread(std::mem_fun(&MyClass::handler),this);
std::thread accepts arguments to the function (which is the first argument) and this is passed as an argument to the mem_fun object, which then calls the handler function on this.
You could also quite simply do the below, courtesy - Start thread with member function
std::thread myThread(&MyClass::handler,this);