I want to be able to define a class with some data members, and a function which has access to those data members, which are to be private.
I then want a public func
foo_func
is a (non-static
) member function, and it needs an instance of foo
on which to operate. This instance must be provided to the thread constructor. If you refer to the std::thread::thread reference page it explains what code is executed in the new thread. The relevant point is that which refers to f
being a pointer to member function:
- If
f
is pointer to a member function of classT
, then it is called. The return value is ignored. Effectively, the following code is executed:
(t1.*f)(t2, ..., tN)
if the type oft1
is eitherT
, reference toT
or reference to type derived fromT
.((*t1).*f)(t2, ..., tN)
otherwise.
so it is clear that the instance is required.
Change to:
for(...) some_threads.push_back(std::thread(&foo::foo_func, this));
Simple example:
#include <iostream>
#include <thread>
#include <vector>
class foo
{
public:
void make_foo_func_threads()
{
for (int i = 0; i < 5; ++i)
some_threads.push_back(std::thread(&foo::foo_func, this));
for (auto& t: some_threads) t.join();
}
private:
void foo_func() { std::cout << "Hello\n"; }
std::vector<std::thread> some_threads;
};
int main()
{
foo f;
f.make_foo_func_threads();
}