Let's say we have some Class SomeAlgorithm
, that has been initialized with a bunch of data and other variables. We now want to use its member function execute
to start computing. Let's create a std::thread
and join
it with the main thread.
#include <thread>
#include <memory>
class SomeAlgorithm {
public:
void execute();
private:
// variables, eg. std::vector<int> data
};
int main() {
// (1)
{
SomeAlgorithm a1;
std::thread t1(&SomeAlgorithm::execute, &a1);
t1.join();
}
// (2)
{
SomeAlgorithm* a2 = new SomeAlgorithm();
std::thread t2(&SomeAlgorithm::execute, a2);
t2.join();
delete a2;
}
// (3)
{
std::unique_ptr<SomeAlgorithm> a3(new SomeAlgorithm());
std::thread t3(&SomeAlgorithm::execute, a3.get());
t3.join();
}
}
What is the preferred way to create such a thread? Are there any best practices? And what is the savest way in terms of memory use that ensures that the allocated memory gets freed?